函数名称:socket_write()
适用版本:PHP 4, PHP 5, PHP 7
用法:socket_write(resource $socket, string $buffer, int $length): int|false
说明:socket_write() 函数用于向一个打开的socket写入数据。它可以用于发送数据到服务器或其他网络设备。
参数:
- $socket:必需,表示一个有效的socket资源,可以通过socket_create()或socket_accept()函数获取。
- $buffer:必需,表示要发送的数据。可以是字符串或二进制数据。
- $length:必需,表示要发送的数据长度。如果未指定,则默认发送整个数据。
返回值:
- 如果成功发送数据,则返回发送的字节数(可能小于指定的$length)。
- 如果发生错误,则返回false。
示例:
// 创建一个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);
在上面的示例中,我们首先创建了一个TCP socket,然后使用socket_connect()函数连接到服务器。然后,我们定义了要发送的数据,并使用socket_write()函数将数据发送到服务器。最后,我们关闭了socket连接。
请注意,socket_write()函数可能不会一次性发送所有数据。因此,我们需要根据返回的字节数来确定实际发送的数据量。如果发送失败,则可以使用socket_strerror()函数获取错误消息。