Phpsocketsocket is located in TCP/IP protocol, provides the client-server mode of asynchronous communication, that is, the client to the server to send a service request, the server received the request, provide the corresponding feedback or service! I practiced one of the most basic examples:
Use and initiate a blocking (block) connection in which the server remains connected if the data stream is not returned, and the connection is immediately disconnected once the data has been passed in. The code is as follows:
Copy Code code as follows:
<?php
$host = www.sohu.com; This address casually, with Sina's line, mainly testing with, which does not matter
$page = "/index.html";
$port = 80;
$request = "Get $page http/1.1\r\n";
$request. = "Host: $host \ r \ n";
$request. = "Referer: $host \ r \ n";
$request. = "connection:close\r\n\r\n";
Allow connection timeout of 1.5 seconds
$connectionTimeout = 1.5;
Allow remote server to complete response within 2 seconds
$responseTimeout = 2;
Establish a socket connection
$fp = Fsockopen ($host, $port, $errno, $errstr, $connectionTimeout);
if (! $fp) {
throw new Exception ("Connection to $hostfailed: $errstr");
} else {
Stream_set_blocking ($fp, true);
Stream_set_timeout ($fp, $responseTimeout);
}
Send Request string
Fwrite ($fp, $request);
Gets the contents of the returned data stream
$content = Stream_get_contents ($FP);
Echo $content;
$meta = Stream_get_meta_data ($FP);
if ($meta [' timed_out ']) {
throw new Exception ("Responsefrom Web Services server timed out.");
}
Turn off the socket connection
Fclose ($FP);
?>