Current Location: Home> Function Categories> stream_socket_pair

stream_socket_pair

Create a pair of exactly the same network socket connection streams
Name:stream_socket_pair
Category:Stream
Programming Language:php
One-line Description:Create a pair of interconnected stream sockets for inter-process communication

Function name: stream_socket_pair()

Function Description: The stream_socket_pair() function creates a pair of interconnected stream sockets for inter-process communication.

Applicable version: PHP 5 >= 5.1.0, PHP 7

Syntax: stream_socket_pair(int $domain, int $type, int $protocol)

parameter:

  • $domain: The domain of the socket (can be AF_INET, AF_INET6, AF_UNIX or AF_INET6)
  • $type: The type of socket (can be SOCK_STREAM or SOCK_DGRAM)
  • $protocol: socket protocol (can be SOL_TCP or SOL_UDP)

Return value:

  • If successful, an array containing two connections is returned, and if failed, a FALSE is returned.

Example:

 // 创建流套接字对$sockets = stream_socket_pair(AF_UNIX, SOCK_STREAM, 0); if ($sockets === false) { echo "创建流套接字对失败"; exit; } // 在父进程中写入数据到套接字$data = "Hello child process!"; fwrite($sockets[0], $data); // 在子进程中读取套接字中的数据$receivedData = fread($sockets[1], strlen($data)); // 输出从父进程传递给子进程的数据echo $receivedData; // 关闭套接字fclose($sockets[0]); fclose($sockets[1]);

In the example above, we first create a convection socket using stream_socket_pair() function. We then write data to the socket in the parent process and read data from the socket in the child process. Finally, we output the data passed from the parent process to the child process and close the socket.

Note that stream_socket_pair() function can only be used on socket-enabled operating systems such as Linux or Unix.

Similar Functions
Popular Articles