此示例是对 范例 中第一个示例的简单重写,以使用 socket_recv()。
<?php
error_reporting(E_ALL);
echo "<h2>TCP/IP 连接</h2>\n";
/* 获取 WWW 服务的端口。 */
$service_port = getservbyname('www', 'tcp');
/* 获取目标主机的 IP 地址。 */
$address = gethostbyname('www.example.com');
/* 创建一个 TCP/IP 套接字。 */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() 失败:原因:" . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}
echo "正在尝试连接到 '$address' 端口 '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() 失败。\n原因:("$result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "正在发送 HTTP HEAD 请求...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "正在读取响应:\n\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
echo "从 socket_recv() 中读取了 "$bytes " 个字节。正在关闭套接字...";
} else {
echo "socket_recv() 失败;原因:" . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);
echo $buf . "\n";
echo "OK.\n\n";
?>
<h2>TCP/IP Connection</h2>
OK.
Attempting to connect to '208.77.188.166' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:
Read 123 bytes from socket_recv(). Closing socket...HTTP/1.1 200 OK
Date: Mon, 14 Sep 2009 08:56:36 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8
OK.