Current Location: Home> Function Categories> stream_socket_accept

stream_socket_accept

Accepts socket connections created by stream_socket_server()
Name:stream_socket_accept
Category:Stream
Programming Language:php
One-line Description:Accepts a socket connection created through the stream_socket_server() function and returns a new socket connection for communication with the client

Function name: stream_socket_accept()

Function Applicable Version: PHP 4 >= 4.1.0, PHP 5, PHP 7

Function description: The stream_socket_accept() function accepts a socket connection created by the stream_socket_server() function and returns a new socket connection for communication with the client.

Syntax: resource stream_socket_accept ( resource $server_socket [, float $timeout = ini_get("default_socket_timeout") [, string &$peername ]] )

parameter:

  • $server_socket: Required. socket resources created through stream_socket_server() function.
  • $timeout: optional. Specifies the timeout time waiting for the client connection, in seconds, the default value is ini_get("default_socket_timeout"), that is, the default timeout time in php.ini.
  • $peername: optional. A string variable used to store the client's IP address and port number.

Return value: If a client connection is successfully accepted, a new socket resource is returned to communicate with the client. If an error occurs, false is returned.

Example: <?php // Create socket server $server = stream_socket_server('tcp://127.0.0.1:8080', $errno, $errstr);

if (!$server) { echo "Cannot create socket server: $errstr ($errno)"; } else { echo "Waiting for client connection...\n";

 // 接受客户端连接$client = stream_socket_accept($server); if (!$client) { echo "无法接受客户端连接"; } else { // 与客户端通信$message = "欢迎连接到服务器"; fwrite($client, $message); // 读取客户端发送的数据$data = fread($client, 1024); echo "接收到客户端数据:$data"; // 关闭客户端连接fclose($client); } // 关闭服务器fclose($server);

} ?> In the above example, first use the stream_socket_server() function to create a socket server and bind it to the local port 8080. Then use the stream_socket_accept() function to wait for the client to connect and return a new socket resource for communication with the client. During communication with the client, use the fwrite() function to send a welcome message to the client, and use the fread() function to read the data sent by the client. Finally, use the fclose() function to close the client connection and the server connection.

Similar Functions
Popular Articles