Php persistent connection, playing is so simple

Source: Internet
Author: User
Tags epoll

Php persistent connection, playing is so simple

When talking about long links, you must be familiar with it, that is, reusing a link for continuous data interaction. Unlike those overnight services, the link needs to be opened and closed frequently, low efficiency also increases business complexity. Many Internet business scenarios require persistent connection support, such as games, chats, and Information Push. Today, we will reveal the php persistent connection method step by step. I believe that the implementation of any technology is based on the needs of business scenarios, so this time we will talk about things in the chat room.

0x00 scalpers

I remember using php to write chat rooms or using polling. Undoubtedly, when talking about polling, some people will say long polling. That's right! Long polling is also very good, but it is difficult to play this on nginx + fpm. After all, a request needs to occupy a php process (even if apache + php_mod is used, it also requires a request for a thread), so it would be okay for a few people to play casually. Once there are more people put online, this is basically useless. Therefore, we still adopt the polling method, so that the process will not be blocked and a request can be immediately responded, but the new problem is that we need to constantly send requests to the server, the larger the interval, the larger the message latency.

0x01 gorgeous Transformation

After experiencing the one-second, one-second, and three-second scenes! So I decided to become a real man. Oh no, it should be a real persistent connection. Fuck polling, fuck long polling, fuck webserver, all back to the edge station, let flash socket (or websocket) to rule the world! Start a long connection journey in the true sense. To use persistent connections, you always have to deal with sockets. As the best language in the world (none), socket encapsulation is indispensable. Just copy the socket _ *** and start it. So we have the following code. Is it a persistent connection? Latency, right? Socket, right? Medical Fee, right? So easy ....

 
 
  1. $sfd = socket_create(AF_INET, SOCK_STREAM, 0); 
  2.  
  3. socket_bind($sfd, "0.0.0.0", 1234); 
  4.  
  5. socket_listen($sfd, 511); 
  6.  
  7. socket_set_option($sfd, SOL_SOCKET, SO_REUSEADDR, 1); 
  8.  
  9. socket_set_nonblock($sfd); 
  10.  
  11. $rfds = array($sfd); 
  12.  
  13. $wfds = array(); 
  14.  
  15. do{ 
  16.  
  17.     $rs = $rfds; 
  18.  
  19.     $ws = $wfds; 
  20.  
  21.     $es = array(); 
  22.  
  23.     $ret = socket_select($rs, $ws, $es, 3); 
  24.  
  25.      
  26.  
  27.     //read event 
  28.  
  29.     foreach($rs as $fd){ 
  30.  
  31.         if($fd == $sfd){ 
  32.  
  33.             $cfd = socket_accept($sfd); 
  34.  
  35.             socket_set_nonblock($cfd); 
  36.  
  37.             $rfds[] = $cfd; 
  38.  
  39.             echo "new client coming, fd=$cfd\n"; 
  40.  
  41.         }else{ 
  42.  
  43.             $msg = socket_read($fd, 1024); 
  44.  
  45.             if($msg <= 0){ 
  46.  
  47.                 //close 
  48.  
  49.             }else{ 
  50.  
  51.                 //recv msg 
  52.  
  53.                 echo "on message, fd=$fd data=$msg\n"; 
  54.  
  55.             } 
  56.  
  57.         } 
  58.  
  59.     } 
  60.  
  61.      
  62.  
  63.     //write event 
  64.  
  65.     foreach($ws as $fd){ 
  66.  
  67.         socket_write($fd, ........); 
  68.  
  69.     } 
  70.  
  71.      
  72.  
  73. }while(true); 

0x02 peak Creation

From the day when I played socket, google told me in a few words that select should not be used in high concurrency; efficiency should be used; iocp should be used for win; epoll should be used for linux, blablablabla... oh! Well, Since google has said this, I cannot compete with his old man. I decided again (Why ?) I want to hear from google and get epoll up, but I can't write it on my own? The whole expansion is better for people like me, and libevent is leaving you! After the crazy co code (py), the masterpiece finally came out of the mountains. How efficient can it be, how much concurrency it can support, and how much concurrency it doesn't make? It's useless to select it anyway. I'm a hero!

 
 
  1. $sfd = stream_socket_server ('tcp://0.0.0.0:1234', $errno, $errstr); 
  2.  
  3. stream_set_blocking($sfd, 0); 
  4.  
  5. $base = event_base_new(); 
  6.  
  7. $event = event_new(); 
  8.  
  9. event_set($event, $sfd, EV_READ | EV_PERSIST, 'ev_accept', $base); 
  10.  
  11. event_base_set($event, $base); 
  12.  
  13. event_add($event); 
  14.  
  15. event_base_loop($base); 
  16.  
  17. function ev_accept($socket, $flag, $base) 
  18.  
  19.  
  20.     $connection = stream_socket_accept($socket); 
  21.  
  22.     stream_set_blocking($connection, 0); 
  23.  
  24.     $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error',  $connection);     
  25.  
  26.     event_buffer_base_set($buffer, $base); 
  27.  
  28.     event_buffer_timeout_set($buffer, 30, 30); 
  29.  
  30.     event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff); 
  31.  
  32.     event_buffer_priority_set($buffer, 10); 
  33.  
  34.     event_buffer_enable($buffer, EV_READ | EV_PERSIST); 
  35.  
  36.  
  37. function ev_error($buffer, $error, $connection) 
  38.  
  39.  
  40.     event_buffer_disable($buffer, EV_READ | EV_WRITE);                 
  41.  
  42.     event_buffer_free($buffer);                 
  43.  
  44.     fclose($connection);                 
  45.  
  46.  
  47. function ev_read($buffer, $connection) 
  48.  
  49.  
  50.     $read = event_buffer_read($buffer, 256); 
  51.  
  52.     //do something.... 
  53.  

0x03 Best Practices

With the increase in the number of people and the increase in concurrency, a single process can no longer meet the demand. The story of Tian boguang tells us that single-picking is not a good fit for a group of P. Why? As the saying goes, things are trivial and stop !! If you don't want to change it, you will lose it. Split it up and split a single process into multiple processes. However, after the split, there are new problems, such as inter-process communication, Server Load balancer, and session uniqueness. Since such a problem has been raised, there must be a solution. There are extensions and libraries available to solve this problem, such as swoole and workerman? Compared with swoole, swoole is more powerful in nature and functions! It seems that the short form is not elegant. Well, the performance and functions are even better (bucket brother, please forgive me for being bored ~).... Wait !!! However, when we use php to develop the web, we do not use the library related to webserver for development, right? It's just a simple echo. All these complicated tasks are handed over to nginx or apache, which is the top of the list, so that we can concentrate on writing logic. For web writing, we only need to simply configure nginx and fpm. What about the socket service? Why can't we simply configure it like nginx + fpm ?? Of course yes, you must be able ..... I am afraid that the advertisement is coming...

0x04 unexpected

Writing a socket service is not more advanced than writing a web service. It is all about coding and completing requirements. The communication layer is fixed, but one is done by nginx and the other is done by yourself .. But now you don't need to do it yourself. Similar to the nginx + fpm solution, fooking + fpm = php persistent connection, gateway is used to carry the connection, router is used to forward messages, and inter-process communication? Load Balancing? Session unique? So easy ..

 
 
  1. $ Sid = $ _ SERVER ['sessionid']; // This is the SESSIONID
  2.  
  3. $ Data = file_get_contents ("php: // input"); // you can get the request content.
  4.  
  5. // Two steps are required to return the message
  6.  
  7. Header ('content-Length: 11'); // number of bytes returned to the client
  8.  
  9. Echo "hello world ";
  10.  
  11. // Send messages to other users
  12.  
  13. Include 'api. php ';
  14.  
  15. $ Router = new RouterClient ('router host', 'router port ');
  16.  
  17. $ Router-> sendMsg (User sessionid, "fuck you ");
  18.  
  19. // You want to send messages to everyone
  20.  
  21. $ Router-> sendAllMsg ("fuck all ");
  22.  
  23. // Send messages to a specified group (similar to pub/sub of redis)
  24.  
  25. $ Router-> publish ("channel name", "fuck all ");

Project address: http://git.oschina.net/scgywx/fooking

Document address (occasionally updated): http://my.oschina.net/scgywx/blog/465186

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.