企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**socket_create_pair** ( int **$domain** , int **$type** , int **$protocol** , array **&$fd** ) : bool — 创建两个已连接且无法区分的套接字,并将其存储在数组(fd)中。 此功能通常在IPC(进程间通信)中使用。成功时返回 TRUE, 或者在失败时返回 FALSE ~~~ $sockets = array(); /* 在Windows上,我们需要使用AF_INET */ $domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX); /* 设置套接字对 */ if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) { echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error()); } /* 发送和接收数据 */ if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) { echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0])); } if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) { echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1])); } var_dump($data); /* 关闭套接字 */ socket_close($sockets[0]); socket_close($sockets[1]); ~~~ IPC例子 ~~~ $ary = array(); $strone = 'Message From Parent.'; $strtwo = 'Message From Child.'; if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) { echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error()); } $pid = pcntl_fork(); if ($pid == -1) { echo 'Could not fork Process.'; } elseif ($pid) { /*parent*/ socket_close($ary[0]); if (socket_write($ary[1], $strone, strlen($strone)) === false) { echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1])); } if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) { echo "Received $strtwo\n"; } socket_close($ary[1]); } else { /*child*/ socket_close($ary[1]); if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) { echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0])); } if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) { echo "Received $strone\n"; } socket_close($ary[0]); } ~~~