Simple analysis of PHP socket technology _php Skills

Source: Internet
Author: User

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);
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.