ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
**stream_context_create** ([ array $options [, array $params ]] ) : resource — 创建数据流上下文,返回上下文资源流 **上下文Context选项和参数的具体值参考**[**官方文档**](https://www.php.net/manual/zh/context.php) options选项可单独通过[stream\_context\_set\_option()](https://www.php.net/manual/zh/function.stream-context-set-option.php)设置,params参数可单独通过[stream\_context\_set\_params()](https://www.php.net/manual/zh/function.stream-context-set-params.php)设置 ~~~php $requestBody = '{"username":"nonfu"}'; $context = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => "Content-Type: application/json;charset=utf-8;\r\nContent-Length: " . mb_strlen($requestBody), 'content' => $requestBody ] ]); $response = file_get_contents('https://my-api.com/users', false, $context); //也可以用于fopen等函数如 $fp = fopen('http://www.example.com', 'r', false, $context); fpassthru($fp); 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)