Server
<?php
Server
Set error handling
Error_reporting (E_all);
Set run time
Set_time_limit (0);
Buffering
Ob_implicit_flush ();
$ip = "127.0.0.1"; IP Address
$port = 1000; Port number
$socket = Socket_create (Af_inet, Sock_stream, sol_tcp); Create a SOCKET
if ($socket)
echo "Socket_create () successed!\n";
Else
echo "Socket_create () failed:". Socket_strerror ($socket). " \ n ";
$bind = Socket_bind ($socket, $ip, $port); Bind a socket
if ($bind)
echo "Socket_bind () successed!\n";
Else
echo "Socket_bind () failed:". Socket_strerror ($bind). " \ n ";
$listen = Socket_listen ($socket); Inter Listening socket
if ($listen)
echo "Socket_listen () successed!\n";
Else
echo "Socket_listen () failed:". Socket_strerror ($listen). " \ n ";
while (true)
{
$msg = Socket_accept ($socket); Accept a socket
if (! $msg)
{
echo "Socket_accept () failed:". Socket_strerror ($msg). " \ n ";
Break
}
$welcome = "Welcome to PHP server!\n";
Socket_write ($msg, $welcome, strlen ($welcome));
while (true)
{
$command = Strtoupper (Trim (Socket_read ($msg, 1024));
if (! $command)
Break
Switch ($command)
{
Case "HELLO":
$writer = "Hello everybody!";
Break
Case "QUIT":
$writer = "Bye-bye";
Break
Case "Help":
$writer = "Hello\tquit\thelp";
Break
Default
$writer = "Error command!";
}
Socket_write ($msg, $writer, strlen ($writer));
if ($command = = "QUIT")
Break
}
Socket_close ($msg);
}
Socket_close ($socket); Close socket
?>