PHP long Connect, playing is so simple _php tutorial

Source: Internet
Author: User
Tags epoll

PHP long connection, playing is so simple


When it comes to long links, we are certainly not unfamiliar, is to reuse a link continuous data interaction, it is not like those one-night stand service, need to open and close the link frequently, inefficient while also increase the complexity of the business. In the crotch a lot of internet business scenarios need long-connected support, such as: games, chat, information, such as push, and so on, today we step-by-step to uncover the PHP long connection play. I believe that the implementation of any technology is due to the needs of business scenarios, so this time we also take the chat room.

0x00 Preliminary Sledgehammer

Remember the previous use of PHP to write chat room or use polling way, no doubt, a mention of polling, there will be someone said long polling, yes! Long polling is also very good, but in nginx+fpm above play this somewhat laborious, after all, a request needs to occupy a PHP process (even with apache+php_mod, also need a request a thread), so if a few people casually play is OK, Once you put it on the line, it's basically useless. So it's polling, so it doesn't block the process, and a request responds immediately, but the new problem is the need to constantly send requests to the server, and the greater the time interval, the greater the message latency.

0x01 Gorgeous body Change

After experiencing the above kind of a second a small card, three seconds a kcal scene! Can not see anymore, so decided to become a real man, oh no, it should be a real long connection. Go fuck polling, go fuck long polling, go fuck webserver, all step aside, let flash socket (or websocket) to rule the world! began a long connected journey in a real sense. To play a long connection always need to deal with the socket, as the world's best language (no one), the socket is naturally the package. Copy up socket_*** to open dry, so there is the following this code, long connection is it? Delay, huh? Socket, right? Soup, right? So easy ....

 
 
  1. $SFD = Socket_create (af_inet, sock_stream, 0);
  2. Socket_bind ($sfd, "0.0.0.0", 1234);
  3. Socket_listen ($sfd, 511);
  4. Socket_set_option ($sfd, Sol_socket, SO_REUSEADDR, 1);
  5. Socket_set_nonblock ($sfd);
  6. $rfds = Array ($sfd);
  7. $wfds = Array ();
  8. Do {
  9. $rs = $rfds ;
  10. $ws = $wfds ;
  11. $es = Array ();
  12. $ret = Socket_select ($rs, $ws, $es, 3);
  13. //read Event
  14. foreach ( $rs as $fd) {
  15. if ($fd = = $sfd) {
  16. $CFD = socket_accept ($sfd);
  17. Socket_set_nonblock ($cfd);
  18. $rfds [] = $CFD ;
  19. Echo "New client coming, fd= $cfd \ n";
  20. }Else{
  21. $msg = Socket_read ($fd, 1024x768);
  22. if ($msg <= 0) {
  23. //close
  24. }Else{
  25. //recv msg
  26. Echo "on message, fd= $fd data= $msg \ n";
  27. }
  28. }
  29. }
  30. //write Event
  31. foreach ( $ws as $fd) {
  32. Socket_write ($fd, ...);
  33. }
  34. }while (true);

0x02 Pinnacle

From the day of playing the socket, Google Whisper told me, high concurrency under the Select Do not use AH, efficiency bottom ah, win to use IOCP Ah, Linux to use Epoll Ah, blablablabla ... Oh! Well, since Google has said so, I can not be serious with his old man is not, another decision (why?) To listen to Google, the epoll up, but can not write their own ah? Like me lazy person or the whole extension good, libevent walk you! After Crazy knitting (CO) code (PY), God finally Mountain, concrete can have more efficient, can support how much concurrency, do not create, anyway useless Select, I played is dick!

 
 
  1. $SFD = Stream_socket_server (' tcp://0.0.0.0:1234 ', $errno, $errstr );
  2. Stream_set_blocking ($sfd, 0);
  3. $base = Event_base_new ();
  4. $event = Event_new ();
  5. Event_set ($event, $sfd, Ev_read | Ev_persist, ' ev_accept ', $base);
  6. Event_base_set ($event, $base);
  7. Event_add ($event);
  8. Event_base_loop ($base);
  9. function ev_accept ($socket, $flag, $base)
  10. {
  11. $connection = stream_socket_accept ($socket);
  12. Stream_set_blocking ($connection, 0);
  13. $buffer = event_buffer_new ($connection, ' ev_read ', NULL, ' Ev_error ' , $connection );
  14. Event_buffer_base_set ($buffer, $base);
  15. Event_buffer_timeout_set ($buffer, +);
  16. Event_buffer_watermark_set ($buffer, ev_read, 0, 0xffffff);
  17. Event_buffer_priority_set ($buffer, ten);
  18. Event_buffer_enable ($buffer, Ev_read | Ev_persist);
  19. }
  20. function ev_error ($buffer, $error, $connection)
  21. {
  22. Event_buffer_disable ($buffer, Ev_read | Ev_write);
  23. Event_buffer_free ($buffer);
  24. Fclose ($connection);
  25. }
  26. function ev_read ($buffer, $connection)
  27. {
  28. $read = Event_buffer_read ($buffer, N.);
  29. //do something ....
  30. }

0X03 Ledge

As the number of people increase, concurrent ascension, a single process has not satisfied the demand, Timberg's story tells us, singled out is not fighting Group P's, the whole? As the saying goes, punches, small, stop!! No more, no more. Split, the single process into a multi-process, but after the demolition and face new problems, inter-process communication, load balancing, session only and so on. Now that the problem has been raised, there must be a solution, ready-made extensions and libraries to solve the matter, such as: Swoole,workerman? By contrast swoole more cock Some, sex, function, uh! It seems that the shorthand is not very good, well, performance and features more dick (brother, please forgive my boring ~) .... Wait a minute!!! 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 the web we just need to simply configure the Nginx and FPM, then write the socket service it? Why can't we just configure as simple as nginx+fpm?? Of course, I must be able to ... Look at this story is afraid of advertising to come ...

0x04 Surprise

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 complete their own, similar to the NGINX+FPM scheme, fooking+fpm=php long connection, gateway for hosting connections, router for forwarding messages, interprocess communication? Load Balancing? The only session? So easy.

 
 
  1. $sid = $_server [' SESSIONID ']; //This is SessionID
  2. $data = file_get_contents ("Php://input");//So we can get the request content.
  3. //Want to return a message in just two steps
  4. Header (' content-length:11 '); //Return to client bytes
  5. Echo "Hello World";
  6. //Want to send messages to other users
  7. include ' api.php ';
  8. $router = New routerclient (' router host', ' router port ');
  9. $router ->sendmsg (User SessionID, "Fuck You");
  10. //Want to give information to everyone
  11. $router ->sendallmsg ("Fuck all");
  12. //Want to send a message to the specified group (pub/sub like Redis)
  13. $router ->publish ("channel name", "Fuck all");

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

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

http://www.bkjia.com/PHPjc/1015229.html www.bkjia.com true http://www.bkjia.com/PHPjc/1015229.html techarticle php Long connection, play is so simple to talk about long links we certainly are not unfamiliar, is to reuse a link continuous data interaction, it is not like those one-night stand service, need frequent ...

  • 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.