Current Location: Home> Function Categories> socket_create_pair

socket_create_pair

Create a pair of indistinguishable sockets and store them in an array
Name:socket_create_pair
Category:Sockets
Programming Language:php
One-line Description:Create a pair of interconnected sockets that can be used to communicate within the same process

Function name: socket_create_pair()

Applicable version: PHP 4, PHP 5, PHP 7

Function Description: The socket_create_pair() function is used to create a pair of interconnected sockets, which can be used to communicate within the same process.

Syntax: bool socket_create_pair(int $domain, int $type, int $protocol, array &$fd)

parameter:

  • $domain: The protocol domain of the socket. Supported protocol domains include AF_INET (IPv4 Network Protocol), AF_INET6 (IPv6 Network Protocol), and AF_UNIX (local UNIX file system socket).
  • $type: The type of the socket. Supported socket types include SOCK_STREAM (stream sockets, reliable, connected-oriented sockets) and SOCK_DGRAM (datagram sockets, connectionless, unreliable sockets).
  • $protocol: socket protocol. It can be IPPROTO_TCP (TCP protocol) or IPPROTO_UDP (UDP protocol).
  • $fd: an array containing two socket file descriptors. After successful creation, the file descriptor for the first socket is stored in $fd[0], while the file descriptor for the second socket is stored in $fd[1].

Return value: Return true if a pair of interconnected sockets are successfully created. If an error occurs, false is returned.

Example:

 // 创建一对相互连接的套接字if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $fd) === false) { echo "套接字创建失败: " . socket_strerror(socket_last_error()) . "\n"; exit; } // 在两个套接字之间进行通信$pid = pcntl_fork(); if ($pid == -1) { echo "进程创建失败\n"; exit; } elseif ($pid == 0) { // 子进程$message = "Hello from child process!"; socket_write($fd[0], $message, strlen($message)); exit; } else { // 父进程$message = socket_read($fd[1], 1024); echo "接收到的消息: " . $message . "\n"; pcntl_wait($status); // 等待子进程结束exit; }

In the above example, first, using socket_create_pair() to create a pair of interconnected sockets and store the file descriptors of the two sockets in the $fd array. Then, a child process is created through pcntl_fork(), and the child process sends a message to the parent process. The parent process reads the message sent by the child process through socket_read() and outputs it to the console. Finally, wait for the child process to end through pcntl_wait().

Similar Functions
Popular Articles