Function name: socket_write()
Applicable version: PHP 4, PHP 5, PHP 7
Usage: socket_write(resource $socket, string $buffer, int $length): int|false
Description: The socket_write() function is used to write data to an open socket. It can be used to send data to a server or other network device.
parameter:
Return value:
Example:
// 创建一个TCP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { // 处理创建socket失败的情况die("Failed to create socket: " . socket_strerror(socket_last_error())); } // 连接到服务器$result = socket_connect($socket, '127.0.0.1', 8080); if ($result === false) { // 处理连接失败的情况die("Failed to connect: " . socket_strerror(socket_last_error($socket))); } // 要发送的数据$data = "Hello, server!"; // 发送数据$bytesSent = socket_write($socket, $data, strlen($data)); if ($bytesSent === false) { // 处理发送失败的情况die("Failed to send data: " . socket_strerror(socket_last_error($socket))); } echo "Sent $bytesSent bytes of data to server."; // 关闭socket连接socket_close($socket);
In the example above, we first create a TCP socket and then connect to the server using the socket_connect() function. Then we define the data to be sent and use the socket_write() function to send the data to the server. Finally, we closed the socket connection.
Note that the socket_write() function may not send all data at once. Therefore, we need to determine the actual amount of data sent based on the number of bytes returned. If the sending fails, you can use the socket_strerror() function to get the error message.