Simple PHP Client Server Socket Program
From Code Trash
Introduction
Server Code. It is best to check these two programs from the command line.
Because i have used scanf like function in the socket client example program which will wait for you to enter input from the keyboard.
Many string constants are used for more detailed explanation of the program.
Socket Server
<? if(isset($_SERVER['SERVER_NAME'])) $nl = '<br>'; else $nl = "\n"; error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); $str = ''; $acc= NULL; echo "$nl Starting up server... $nl"; $s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if(!$s)die("$nl Unable to create socket"); if(!socket_bind($s,'127.0.0.1',63254)) die("$nl Trying to Bind: ".socket_strerror(socket_last_error())); if(!socket_listen($s,10)) die(socket_strerror(socket_last_error())); echo $nl; echo "$nl Listening ..."; $inc = 0; while(++$inc) { echo "$nl Waiting for connection(s)..."; $acc = socket_accept($s); echo "$nl Connection $inc has been made $nl"; if(!$acc)die(socket_strerror(socket_last_error())); while(1) { $str = socket_read($acc,512); echo $str; if($str===false)die(socket_strerror(socket_last_error())); if($str=="exit\r\n" || $str=="quit\r\n")break; } socket_close($acc); echo "$nl Connection $inc closed $nl"; if($str=="quit\r\n")break; } socket_close($s); echo "$nl Closed Server"; ?>
Socket Client
<? set_time_limit(0); $f = fsockopen('127.0.0.1',63254,$a,$b,10); if(!$f)die("\nCannot connect"); echo "\nConnected: \n"; while(1) { $buff = fgets(STDIN); fwrite($f,$buff); if($buff=="exit\r\n")break; } fclose($f); ?>