Current Location: Home> Function Categories> socket_shutdown

socket_shutdown

Close the socket to receive, send or both
Name:socket_shutdown
Category:Sockets
Programming Language:php
One-line Description:Close an already opened socket connection

Function name: socket_shutdown()

Function description: socket_shutdown() function is used to close an already opened socket connection.

Applicable version: This function is available in PHP 4.1.0 and above.

Syntax: bool socket_shutdown ( resource $socket [, int $how = 2 ] )

parameter:

  • $socket: Required, a valid socket resource, indicating the socket connection to be closed.
  • $how: Optional, specify how to close the connection. The default is 2, which means that read and write are turned off. There are three optional values:
    • 0: Close reading.
    • 1: Close writing.
    • 2: Turn off reading and writing.

Return value: Return true if the closing is successful. If an error occurs, false is returned.

Example:

 // 创建一个TCP socket连接$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 连接到远程服务器$connect = socket_connect($socket, '127.0.0.1', 8080); if (!$connect) { echo "连接失败:" . socket_strerror(socket_last_error()) . "\n"; exit; } // 向服务器发送数据$data = "Hello, server!"; socket_write($socket, $data, strlen($data)); // 关闭写入通道,仍然可以接收数据socket_shutdown($socket, 1); // 从服务器接收数据$response = socket_read($socket, 1024); echo "服务器响应:$response\n"; // 关闭socket连接socket_close($socket);

In the above example, a TCP socket connection is first created and connected to a remote server. Then send data to the server and close the write channel, but the data can still be received. Finally, receive data from the server, output the server's response, and close the socket connection.

Please note that the IP address and port number in the example are for reference only and need to be modified according to the specific situation when using it.

Similar Functions
Popular Articles