企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# [网站功能实现](https://www.cnblogs.com/lichihua/diary/2019/03/31/10630377.html) 服务器端代码 ~~~php <?php //设置不超时 set_time_limit(0); class SocketServer { public function __construct($port) { global $errno, $errstr; $socket = stream_socket_server('tcp://127.0.0.1:'.$port, $errno, $errstr); while($conn = stream_socket_accept($socket, -1)) { $buff = ''; $data = ''; //读取请求数据直到遇到\r\n结束符 while(!preg_match('#\r\n#', $buff)) { $buff = fread($conn, 1024); $data .= preg_replace('#\r\n#', '', $buff); } fwrite($conn, $data); fclose($conn); } fclose($socket); } } new SocketServer(1212); ~~~ 客户端: ~~~php <?php if(isset($argv[1])) { $msg = $argv[1]; $socket = stream_socket_client('tcp://127.0.0.1:1212', $errno, $errstr); if(!$socket) { die($errno.$errstr); } else { // stream_set_blocking($socket, 0); for($index = 0; $index < 3; $index++) { 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); fclose($socket); } } else { for($index = 0; $index < 3; $index++) { system('PHP '.__FILE__." $index:test"); } } ~~~ cli运行效果 ![](https://img.kancloud.cn/b2/d5/b2d57d993163c32251da9f273486cc2b_640x431.png) 去掉13行的设置非阻塞模式的代码后,客户端由于设置了usleep()延时,无法写入服务器返回的数据。 当然在客户端不在乎接受结果的情况下,可以使用非阻塞模式来获得最大效率。 ![](https://img.kancloud.cn/77/fa/77fa85aaff730427fa1dd2f9a8b495b7_835x442.png)