<?php server_time_limit(0); // open a server on port 10000 $server_addr="tcp://0.0.0.0:10000"; $server = stream_socket_server($server_addr, $errno, $errorMessage); if ($server === false) { debug("Could not bind to socket: $errorMessage"); exit; } debug("Server listens successfully on $server_addr - press Ctrl-C to stop it"); $client_socks = array(); while(true) { //prepare readable sockets $read_socks = $client_socks; $read_socks[] = $server; //start reading and use a large timeout if(!stream_select ( $read_socks, $write, $except, 300000 )) { die('something went wrong while selecting'); } //new client if(in_array($server, $read_socks)) { $new_client = stream_socket_accept($server); if ($new_client) { //print remote client information, ip and port number debug('New Connection accepted from ' . stream_socket_get_name($new_client, true) ); $client_socks[] = $new_client; debug( "Now there are total ". count($client_socks) . " clients connected"); } //delete the server socket from the read sockets unset($read_socks[ array_search($server, $read_socks) ]); } //message from existing client foreach($read_socks as $sock) { $data = fread($sock, 128); $ip=stream_socket_get_name($client_socks[ array_search($sock, $client_socks) ], true); if(!$data) { unset($client_socks[ array_search($sock, $client_socks) ]); @fclose($sock); debug( "A client ($ip) disconnected. Now there are total ". count($client_socks) . " clients.n"); continue; }else { //----------------------------------------------------------------------------------------------------------------------------------- //data process here //data process end here //----------------------------------------------------------------------------------------------------------------------------------- debug("$ip: ".$data); } //send the message back to client fwrite($sock, $data); } } function debug($s) { $d=date("Y-m-d H:i:s"); echo "\r\n $d - : ".$s; } ?>
2015-10-09