Home  >  Article  >  Backend Development  >  A brief analysis of PHP Socket technology_PHP tutorial

A brief analysis of PHP Socket technology_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:59:58779browse

phpsocketSocket is located in the transmission control protocol of the TCP/IP protocol and provides asynchronous communication in the client-server mode, that is, the client sends a service request to the server, and after the server receives the request, it provides corresponding feedback or service! I practiced a most basic example:

Use and initiate a blocking (block) connection, that is, if the server does not return a data stream, it will remain connected. Once a data stream comes in, it will disconnect immediately after obtaining the content. The code is as follows:

Copy code The code is as follows:

$host = www.sohu.com ; //This address is arbitrary, you can use Sina's, it's mainly for testing, it doesn't matter which one
$page = "/index.html";
$port = 80;
$request = "GET $ page HTTP/1.1rn";
$request .= "Host: $hostrn";
//$request .= "Referer:$hostrn";
$request .= "Connection: closernrn";
//Allow the connection timeout to be 1.5 seconds
$connectionTimeout = 1.5;
//Allow the remote server to complete the response within 2 seconds
$responseTimeout = 2;
//Create 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);
//Get the returned data stream content
$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.");
}
//Close the Socket connection
fclose($ fp);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328092.htmlTechArticlephpsocketSocket is located in the transmission control protocol of the TCP/IP protocol and provides asynchronous communication in the client-server mode, that is, the client communicates with the server Issue a service request. After the server receives the request, it provides the corresponding...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn