How PHP sockets enable long connections

Source: Internet
Author: User
Tags php programming
What is a long connection?

Friends should have seen a lot of online chat tools and web chat tools. The school has a familiar function, if someone replies you, the site will immediately appear prompt, at this time you do not refresh the page, Gmail also has this feature, if the mailbox received a new mail, the site will immediately remind you, even if your page has not been refreshed. When it comes to this, it's definitely not a stranger, it's the reuse of a link for continuous data interaction. In many of the Internet business scenarios now require long-connected support, such as: games, chat, information push and so on, so many similar functions are inseparable from the long connection. The previous section introduces the PHP socket communication, this chapter describes the PHP socket long connection.

Long connections and short links

Short connection is generally a single request data, the server can not take the initiative to "push" the data to the client, but with a long connection is much better, the use of back-end and front-end technology combination, can realize the server "push information" function, if the database has updates, the backend program can immediately put the data "push out", Instead of repeatedly requesting, multiple connections are established, and multiple disconnects.

There are several explanations for the following:

    1. The so-called long connection refers to the establishment of the socket connection, regardless of whether or not to remain connected, but the security is poor; so-called short connection refers to the connection after the socket is set up and after receiving data, the general bank uses short connection

    2. A long connection is a connection that is maintained in TCP-based communication, regardless of whether the data is currently being sent or received. A short connection is a connection that is only made when there is data transfer, and the client-server communication/Transfer data is closed when the connection is completed.

    3. Communication mode
      There are two types of connections between the various network elements: long connections and short connections. The so-called long connection, refers to a TCP connection can be continuously sent multiple packets, during the TCP connection remains, if no packet is sent, both sides need to send a detection packet to maintain this connection. Short connection refers to the communication between the two sides of the data interaction, a TCP connection is established, after the data is sent, the TCP connection is disconnected, that is, each TCP connection completes only a pair of CMPP messages sent.
      At present, it is necessary to use long-connected communication mode between ISMG, and it is recommended to use long connection between SP and ISMG.

    4. Short connection: For example, HTTP, just connect, request, close, the process time is short, the server will not receive a request for a period of time to close the connection. Long connections: Some services need to be connected to the server for a long time, such as CMPP, which usually needs to be maintained online.

Implementing a Long socket connection

Every time we access the PHP script, we get back the results when all the PHP scripts have been executed. If we need a script to run continuously, then we have to use the long connection of PHP to achieve the purpose of running.

If you want to play a long connection, you need to deal with the socket, the socket is naturally less than the package. The following is a long socket connection via code.

In fact the example code is as follows:

<?PHP$SFD = Socket_create (af_inet, sock_stream, 0);  Socket_bind ($SFD, "0.0.0.0", 1234);  Socket_listen ($SFD, 511);  Socket_set_option ($SFD, Sol_socket, SO_REUSEADDR, 1);  Socket_set_nonblock ($SFD);  $rfds = Array ($SFD);  $wfds = Array ();      do{$rs = $rfds;      $ws = $wfds;      $es = Array ();            $ret = Socket_select ($rs, $ws, $es, 3);             Read Event foreach ($rs as $FD) {if ($fd = = $SFD) {$cfd = Socket_accept ($SFD);              Socket_set_nonblock ($CFD);              $rfds [] = $CFD;          echo "New client coming, fd= $CFD \ n";              }else{$msg = Socket_read ($FD, 1024); if ($msg <= 0) {//close}else{echo "on message, fd= $FD da              Ta= $msg \ n ";      }}}//write event foreach ($ws as $FD) {socket_write ($FD, ...); }}while (true);? 

to increase the efficiency below:

&LT;?PHP$SFD = Stream_socket_server (' tcp://0.0.0.0:1234 ', $errno, $ERRSTR);  Stream_set_blocking ($SFD, 0);  $base = Event_base_new ();  $event = Event_new (); Event_set ($event, $SFD, Ev_read |  Ev_persist, ' ev_accept ', $base);  Event_base_set ($event, $base);  Event_add ($event);  Event_base_loop ($base);      function ev_accept ($socket, $flag, $base) {$connection = Stream_socket_accept ($socket);      Stream_set_blocking ($connection, 0);          $buffer = Event_buffer_new ($connection, ' Ev_read ', NULL, ' Ev_error ', $connection);      Event_buffer_base_set ($buffer, $base);      Event_buffer_timeout_set ($buffer, 30, 30);      Event_buffer_watermark_set ($buffer, Ev_read, 0, 0XFFFFFF);      Event_buffer_priority_set ($buffer, 10); Event_buffer_enable ($buffer, Ev_read |  Ev_persist); } function Ev_error ($buffer, $error, $connection) {event_buffer_disable ($buffer, Ev_read |                      Ev_write);                      Event_buffer_free ($buffer);       Fclose ($connection);           } function Ev_read ($buffer, $connection) {$read = Event_buffer_read ($buffer, 256); Do something ...}? >

As the number of people increase, concurrent ascension, a single process has not satisfied the demand, ready-made extensions and libraries to solve this matter, such as: Swoole,workerman? However, when we use PHP to develop the web, we do not use webserver-related libraries to do development right? I'm just a simple echo. These miscellaneous things to Nginx or Apache, they are not hesitate to top in front, so that we can concentrate on writing logic. Write socket service is not higher than writing the web, are playing code, are the completion of requirements, communication that layer is fixed, but one by Nginx complete, the other by themselves to complete. But now do not need to do their own, similar to the NGINX+FPM scheme, fooking+fpm=php long connection, gateway for hosting connections, router for forwarding messages.

Its code is as follows:

<?php$sid = $_server[' SESSIONID '];//This is SESSIONID  $data = file_get_contents ("Php://input");//So we can get the request content.  It only takes two steps to return  the message (' content-length:11 ');//Returns the number of bytes to  the client echo "Hello World";  Want to send messages to other users  include ' api.php ';  $router = new Routerclient (' Router host ', ' Router port ');  $router->sendmsg (user SessionID, "fuck You");  Want to give everyone a message  $router->sendallmsg ("Fuck All");  Want to send a message to the specified group (pub/sub like Redis)  $router->publish ("channel name", "Fuck All");? >

"Related tutorials Recommended"

1. "Php.cn lonely Nine Cheap (4)-php video Tutorial"

2. PHP programming from getting started to mastering the full set of tutorials

Related Article

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.