PHPSocket _ PHP Tutorial

Source: Internet
Author: User
PHPSocket technology. PhpsocketSocket is based on the TCPIP transmission control protocol. It provides client-server mode asynchronous communication, that is, after the client sends a service request to the server and the server receives the request, the phpsocketSocket provides the transmission control protocol based on the TCP/IP protocol and the client-server mode for asynchronous communication. that is, after the client sends a service request to the server and the server receives the request, provide corresponding feedback or services! I practiced a basic example:

Use and initiate a blocking connection, that is, if the server does not return data streams, the connection is maintained. Once a data stream is passed in, the connection is immediately disconnected after the content is obtained. The code is as follows:

The code is as follows:


$ Host = www.sohu.com; // This address can be used for testing.
$ 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 ";
// The allowed connection timeout is 1.5 seconds.
$ ConnectionTimeout = 1.5;
// Allow the remote server to respond 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 the request string
Fwrite ($ fp, $ request );
// Obtain 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 );
?>

...

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.