💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**stream_socket_client** ( string $remote_socket [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") [, int $flags = STREAM_CLIENT_CONNECT [, resource $context ]]]]] ) : resource — **打开** 网络或Unix域套接字 **连接** ~~~ $fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); } fclose($fp); } ~~~ 从本地主机上的UDP服务“daytime”(端口13)检索日期和时间 ~~~ $fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr); if (!$fp) { echo "ERROR: $errno - $errstr<br />\n"; } else { fwrite($fp, "\n"); echo fread($fp, 26); fclose($fp); } ~~~ 例子: 服务器端代码 ~~~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)