PHP ソケット プログラミングによる読み取り完了後の書き込みブロック
サーバー側のコードは次のとおりです:
<br /> <?php<br /> set_time_limit(0);<br /> <br /> $host = "127.0.0.1";<br /> $port = 12345;<br /> <br /> $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket<br /> <br /> $result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口<br /> <br /> $result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接<br /> <br /> $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信<br /> <br /> //若换成循环接收数据,客户端将一直处理等待接收状态<br /> $input = socket_read($spawn, 1024) or die("Could not read data\n");<br /> /* <br /> while (( $data = socket_read($spawn, 1024)) != false) <br /> $input .= $data;<br /> */ <br /> <br /> echo 'input:', strlen($input), "\n";<br /> <br /> $output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果<br /> <br /> echo "output:", $output, "\n";<br /> <br /> // 数据传送 向客户端写入返回结果<br /> socket_write($spawn, $output, strlen($output)) or die("Could not write output\n"); <br /> <br /> // 关闭sockets<br /> socket_close($spawn);<br /> socket_close($socket);
<br /> <?php<br /> <br /> set_time_limit(0);<br /> <br /> $host = "127.0.0.1";<br /> $port = 12345;<br /> <br /> $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socket\n"); // 创建一个Socket<br /> <br /> $connection = socket_connect($socket, $host, $port) or die("Could not connet server\n"); // 连接<br /> <br /> socket_write($socket, "time") or die("Write failed\n"); // 数据传送 向服务器发送消息<br /> <br /> echo 'wait for data';<br /> <br /> while (($buffer = socket_read($socket, 1024))!=false) {<br /> echo("Data sent was: time\nResponse was:" . $buffer . "\n");<br /> }<br /> <br /> socket_close($socket);<br />