lemonade
where dream meets reality
Contoh sederhana Aplikasi chatting Menggunakan PHP Socket
Categories: php

Contoh client-server chatting (single client) menggunakan PHP socket.

Server.php

<?php
//The Server
error_reporting(E_ALL);
$address = “127.0.0.1”;
$port = “10000”;

/* create a socket in the AF_INET family, using SOCK_STREAM for TCP
connection */

$mysock = socket_create(AF_INET, SOCK_STREAM, 0);

// if socket is uses, we reuse it
if (!socket_set_option($mysock, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($mysock));
exit;
}
socket_bind($mysock, $address, $port);
socket_listen($mysock, 5);
$client = socket_accept($mysock);
socket_set_nonblock($client);
$status = 1;

$i = 0;
while (1)
{
$input = “”;

if($status == 0)
{
$client = socket_accept($mysock);
socket_set_nonblock($client);
$status = 1;
}

else if ($status == 1)
{
socket_write($client, “hello!\n”, 10);
$input = socket_read($client, 2048, 1);
if($input != “”)
{
$i++;
echo “Sending $i to client.\n”;
socket_write($client, $i, strlen($i));

echo “Response from client is: $input\n”;
socket_close($client);
$status = 0;
}
}
}
socket_close($mysock);

?>

Client.php

<?php
//The Client
error_reporting(E_ALL);

$address = “127.0.0.1”;
$port = 10000;

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo “socket_create() failed: reason: ” .
socket_strerror(socket_last_error()) . “\n”;
} else {
echo “socket successfully created.\n”;
}

echo “Attempting to connect to ‘$address’ on port ‘$port’…”;
$result = socket_connect($socket, $address, $port);
if ($result === false) {
echo “socket_connect() failed.\nReason: ($result) ” .
socket_strerror(socket_last_error($socket)) . “\n”;
} else {
echo “successfully connected to $address.\n”;
}

$msg = “hello world!”;

echo “Sending $msg to server.\n”;
socket_write($socket, $msg, strlen($msg));

$input = socket_read($socket, 2048);
echo “Response from server is: $input\n”;

echo “Closing socket…”;
socket_close($socket);
?>

Tags:, ,

1 Comment to “Contoh sederhana Aplikasi chatting Menggunakan PHP Socket”

  1. […] contoh sederhana aplikasi chatting menggunakan socket (link). Categories: apaan sih? […]

Leave a Reply