Home > Backend Development > PHP Tutorial > How to implement long connection in php socket

How to implement long connection in php socket

伊谢尔伦
Release: 2023-03-07 20:38:01
Original
25535 people have browsed it

What is a long connection?

Friends should have seen many online chat tools and web online chat tools. There is a familiar function in the school. If someone replies to you, a prompt will appear immediately on the website. You have not refreshed the page at this time. Gmail also has this function. If a new email is received in the mailbox, the website will remind you immediately, even if you The web page has never been refreshed. Speaking of which, everyone must be familiar with this, which is to reuse a link for continuous data interaction. Nowadays, many Internet business scenarios require the support of long connections, such as games, chats, information push, etc. So many similar functions are inseparable from long connections. The previous chapter introduced php socket communication, this chapter will introduce the php socket long connection.

Long connections and short links

Short connections generally request data from a single item. The server cannot actively "push" the data to the client, but with a long connection Much better, using the combination of back-end and front-end technologies, the server's "push information" function can be realized. If there is an update in the database, the back-end program can "push out" the data immediately, instead of repeatedly requesting it multiple times. The connection is established and disconnected multiple times.

There are probably several explanations as follows:

  1. The so-called long connection refers to maintaining the connection regardless of whether it is used or not after establishing a SOCKET connection, but the security is poor; the so-called short connection Connection refers to establishing a SOCKET connection and disconnecting immediately after sending and receiving data. Generally, banks use short connections

  2. Long connections refer to maintaining connections in TCP-based communications. Regardless of whether data is currently being sent or received. The short connection means that the connection is only made when there is data transmission, and the connection is closed after the client-server communication/transmission of data is completed.

  3. Communication method
    There are two connection methods between each network element: long connection and short connection. The so-called long connection means that multiple data packets can be sent continuously on a TCP connection. During the period when the TCP connection is maintained, if no data packets are sent, both parties need to send detection packets to maintain the connection. A short connection means that when the communicating parties have data exchange, a TCP connection is established. After the data is sent, the TCP connection is disconnected. That is, each TCP connection only completes the sending of a pair of CMPP messages.
    At this stage, it is required that ISMGs must use long-term connection communication methods. It is recommended that long-term connection communication methods be used between SPs and ISMGs.

  4. Short connection: For example, http, it only connects, requests, and closes. The process time is short. If the server does not receive the request within a period of time, it can close the connection. Long connection: Some services need to connect to the server for a long time, such as CMPP, and generally need to be maintained online by themselves.

Realizing socket long connection

Every time we access a PHP script, we will wait until all PHP scripts are executed. Get the return result. If we need a script to run continuously, then we must use PHP long connection to achieve the purpose of operation.

If you want to play with long connections, you need to deal with sockets. Socket encapsulation is naturally indispensable. Below is the code to perform a long socket connection.

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);        
    //读取事件 
    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 data=$msg\n";  
            }  
        }  
    } 
  
    //写入事件 
    foreach($ws as $fd){  
        socket_write($fd, ........);  
    }       
}while(true);
?>
Copy after login

Let’s improve the efficiency:

<?php
$sfd = stream_socket_server (&#39;tcp://0.0.0.0:1234&#39;, $errno, $errstr);  
stream_set_blocking($sfd, 0);  
$base = event_base_new();  
$event = event_new();  
event_set($event, $sfd, EV_READ | EV_PERSIST, &#39;ev_accept&#39;, $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, &#39;ev_read&#39;, NULL, &#39;ev_error&#39;,  $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....  
}
?>
Copy after login

Follow As the number of people increases and concurrency increases, a single process can no longer meet the demand. There are ready-made extensions and libraries to solve this problem, such as: swoole, workerman, etc.? However, when we use PHP to develop the web, we do not use webserver-related libraries for development, right? We just do a simple echo. These complicated things are all handed over to nginx or apache, and they take the lead without hesitation, so that we can concentrate on writing logic. Writing socket services is no more advanced than writing web services. They are all coding and completing requirements. The communication layer is fixed, but one is completed by nginx and the other is completed by yourself. . But now you don’t need to complete it yourself. A solution similar to nginx+fpm, fooking+fpm=php long connection, gateway is used to carry the connection, and router is used to forward messages.

The code is as follows:

<?php
$sid = $_SERVER[&#39;SESSIONID&#39;];//这是sessionid  
$data = file_get_contents("php://input");//这样就能拿到请求内容了  
//想要返回消息只需要两步  
header(&#39;Content-Length: 11&#39;);//返回给客户端字节数  
echo "hello world";  
//想要给别的用户发消息  
include &#39;api.php&#39;;  
$router = new RouterClient(&#39;router host&#39;, &#39;router port&#39;);  
$router->sendMsg(用户sessionid, "fuck you");  
//想要给所有人要消息  
$router->sendAllMsg("fuck all");  
//想给指定组发消息(类似redis的pub/sub)  
$router->publish("channel name", "fuck all");
?>
Copy after login

[Related tutorial recommendations]

1. "php.cn Dugu Jiujian (4 )-php video tutorial

2. A complete set of tutorials on PHP programming from entry to master

The above is the detailed content of How to implement long connection in php socket. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template