note 110045 deleted from sockets.examples by danbrown

From: Date: Fri, 14 Sep 2012 21:19:07 +0000
Subject: note 110045 deleted from sockets.examples by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190777@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- I have updated javier's example (multi-client listener) with following fixes: - changed comments and outputed messages back to English, - fixed socket_read() problem -- now it issues two warnings, when client disconects, but continue to listen; in original code, when you connected your listener with a webbrowser and canceled navigation or timeout occured, listener killed itself with fatal PHP error; this is no fixed, - changed socket address to 0.0.0.0 to listen every traffic, including outter one, not just local host / local network traffic, - removed some obvious comments and did some minor code changes. Here is an updated example: <?php error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); $address = '0.0.0.0'; $port = 7777; if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { echo "socket_create() failed, because: : ".socket_strerror(socket_last_error())."\n"; } if (socket_bind($sock, $address, $port) === false) { echo "socket_bind() failed, because: : ".socket_strerror(socket_last_error($sock))."\n"; } if (socket_listen($sock, 5) === false) { echo "socket_listen() failed, because: : ".socket_strerror(socket_last_error($sock))."\n"; } //clients array $clients = array(); do { $read = array(); $read[] = $sock; $read = array_merge($read,$clients); if(socket_select($read,$write = NULL, $except = NULL, $tv_sec = 5) < 1) continue; // Handle new Connections if (in_array($sock, $read)) { if (($msgsock = socket_accept($sock)) === false) { echo "socket_accept() failed, because: : ".socket_strerror(socket_last_error($sock))."\n"; break; } $clients[] = $msgsock; $key = array_keys($clients, $msgsock); $msg = "\nWelcome! Assigned client number is: {$key[0]}\n"."Type 'quit' to end session or 'shutdown' to end listener.\nAnything else, you type will be outputed back to you!\n\n"; socket_write($msgsock, $msg, strlen($msg)); } // Handle Input foreach ($clients as $key => $client) { if (in_array($client, $read)) { if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) { echo "socket_read() failed, because: : ".socket_strerror(socket_last_error($client))."\n"; unset($clients[$key]); break; } if (!$buf = trim($buf)) continue; if ($buf == 'quit') { unset($clients[$key]); socket_close($client); break; } if ($buf == 'shutdown') { socket_close($client); break 2; } $talkback = "Client {$key} sent: '$buf'.\n"; socket_write($client, $talkback, strlen($talkback)); echo($buf."\n"); } } } while (true); socket_close($sock); ?>

« previous php.notes (#190777) next »