Refer to the PHP stream to implement the server client model:
http://php.net/manual/en/book.stream.php
http://blog.csdn.net/shagoo/article/details/6396089
Server-side code:
1<?PHP2 //setting does not time out3 Set_time_limit(0);4 5 classSocketserver6 {7 Public function__construct ($port)8 {9 Global $errno,$errstr;Ten One $socket=Stream_socket_server(' tcp://127.0.0.1: '.$port,$errno,$errstr); A while($conn=stream_socket_accept($socket,-1)) - { - $buff= ' '; the $data= ' '; - - //read request data until \ r \ n Terminator is encountered - while(!Preg_match(' #\r\n# ',$buff)) + { - $buff=fread($conn, 1024); + $data.=Preg_replace(' #\r\n# ', ',$buff); A } at fwrite($conn,$data); - fclose($conn); - } - fclose($socket); - } - } in - NewSocketserver (1212);
Client
1<?PHP2 3 if(isset($argv[1]))4 {5 $msg=$argv[1];6 $socket=stream_socket_client(' tcp://127.0.0.1:1212 ',$errno,$errstr);7 if(!$socket)8 {9 die($errno.$errstr);Ten } One Else A { - //stream_set_blocking ($socket, 0); - for($index= 0;$index< 3;$index++) the { - fwrite($socket, "Client:$msg $index"); - Usleep(100000); - } + fwrite($socket, "\ r \ n"); - $response=fread($socket, 1024); + file_put_contents(' Log.txt ',Date("[H:i:s]", Time()).$response." \ n ",file_append); A fclose($socket); at } - } - Else - { - for($index= 0;$index< 3;$index++) - { in system(' PHP '.__file__."$index: Test "); - } to}
Operating effect under CLI
After removing 13 lines of code that set the non-blocking mode, the client cannot write to the data returned by the server because of the usleep () delay.
Of course, the non-blocking mode can be used for maximum efficiency in cases where the client does not care about accepting the result.
PHP Socket Implementation WebSocket (c) Stream implementation