Current Location: Home> Function Categories> socket_listen

socket_listen

Listen to connections on sockets
Name:socket_listen
Category:Sockets
Programming Language:php
One-line Description:Mark a socket as a passive socket and start listening for connection requests

Function name: socket_listen()

Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7

Function description: The socket_listen() function is used to mark a socket as a passive socket and start listening for connection requests.

Syntax: bool socket_listen ( resource $socket [, int $backlog = 0 ] )

parameter:

  • $socket: Required, socket resource, created via socket_create().
  • $backlog: Optional, specify the maximum number of waiting connections, the default is 0, indicating the system's default connection queue length.

Return value: Return true on success, and false on failure.

Example:

 // 创建套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { die("套接字创建失败: " . socket_strerror(socket_last_error())); } // 绑定套接字到IP和端口$bind = socket_bind($socket, '127.0.0.1', 8080); if ($bind === false) { die("套接字绑定失败: " . socket_strerror(socket_last_error($socket))); } // 开始监听连接请求$listen = socket_listen($socket, 5); if ($listen === false) { die("监听失败: " . socket_strerror(socket_last_error($socket))); } echo "正在监听连接请求...\n"; // 接受客户端连接$clientSocket = socket_accept($socket); if ($clientSocket === false) { die("接受连接失败: " . socket_strerror(socket_last_error($socket))); } echo "已接受客户端连接。\n"; // 关闭套接字socket_close($socket);

In the example above, we first create a socket and then bind it to the local IP address and port. Next, use the socket_listen() function to start listening for connection requests, which marks the socket as a passive socket and specifies the maximum number of waiting connections to be 5. Then, we use the socket_accept() function to accept connections from the client.

Please note that the error handling in the example is for reference only, and appropriate error handling may be required in actual applications according to the specific situation.

Similar Functions
Popular Articles