Function name: socket_close()
Function Description: The socket_close() function closes an open socket resource.
Applicable version: PHP 4, PHP 5, PHP 7
Syntax: bool socket_close ( resource $socket )
parameter:
Return value: Return true if the socket is successfully closed, otherwise false.
Example:
// 创建一个TCP套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 绑定套接字到指定的IP地址和端口$bind = socket_bind($socket, '127.0.0.1', 8080); // 监听连接请求$listen = socket_listen($socket); // 接受客户端连接$clientSocket = socket_accept($socket); // 读取客户端发送的数据$data = socket_read($clientSocket, 1024); // 关闭客户端套接字socket_close($clientSocket); // 关闭服务器套接字socket_close($socket);
In the example above, we first create a TCP socket using socket_create(). Then use socket_bind() to bind the socket to the specified IP address and port. Next, use socket_listen() to listen for connection requests.
When there is a client connection, we use socket_accept() to accept the connection and save the client socket in the $clientSocket variable. Then, use socket_read() to read the data from the client socket.
Finally, use socket_close() to close the client socket and server socket to free up resources.
Please note that the error handling in the example is omitted, and appropriate error handling code should be added in actual use to handle possible error situations.