Real time push based on workerman (no ajax polling)

Let's start with:


TCP/IP is a protocol group, which can be divided into three layers: network layer, transport layer and application layer.

There are IP protocol, ICMP Protocol, ARP protocol, RARP protocol and BOOTP protocol in the network layer.

There are TCP protocol and UDP protocol in the transport layer.

In the application layer, there are:

TCP includes FTP, HTTP, TELNET, SMTP and other protocols

UDP includes DNS, TFTP and other protocols

Short connection

Connect - > transfer data - > close connection

HTTP is stateless. Every time the browser and server perform HTTP operation, they establish a connection, but the connection will be interrupted when the task ends.

It can also be said as follows: short connection refers to disconnection immediately after receiving data after sending after SOCKET connection.

Long connection

Connect - > transfer data - > keep connection - > transfer data - >... ->Close the connection.

Long connection means that the connection is maintained no matter whether it is used or not after the SOCKET connection is established, but the security is poor.

Long connection of http

HTTP can also establish long connection. Use connection: keep alive. HTTP 1.1 defaults to persistent connection. The biggest difference between HTTP1.1 and http1.0 is that they add persistent connection support (it seems that the latest http1.0 can display the specified keep alive), but they are stateless or untrustworthy.

When to use long connection and short connection?

Long connections are often used for frequent operation, point-to-point communication, and the number of connections cannot be too many,. Each TCP connection needs three-step handshake, which takes time. If each operation is connected first and then operated, the processing speed will be reduced a lot. Therefore, each operation will be continuously opened after completion. It is OK to send data packets directly during the second processing without establishing a TCP connection. For example: long connection is used for database connection. Frequent communication with short connection will cause socket error, and frequent socket creation is also a waste of resources.

The http services like WEB sites generally use short links, because long connections will consume a certain amount of resources for the server, while the connections of tens of thousands or even hundreds of millions of clients such as WEB sites use short connections to save some resources. If you use long connections, and there are thousands of users at the same time, if each user occupies a connection, you can imagine it . Therefore, there is a large amount of concurrency, but each user does not need to operate frequently.

Workerman is an open source and high-performance PHP socket server framework developed in pure PHP. It is widely used in the development of mobile app, mobile communication, wechat applet, mobile game server, online game, PHP chat room, hardware communication, smart home, Internet of vehicles, Internet of things and other fields. It supports TCP long connection, Websocket, HTTP and other protocols, and custom protocols. It has asynchronous Mysql, asynchronous Redis, asynchronous HTTP, asynchronous message queue and many other high-performance components.

Start to get to the point: in order to achieve real-time communication, we often use ajax polling mechanism, as shown in the figure:

Later, it can be implemented in the way of workerman. The project is also written by tp, as the official manual says

In combination with other mvc frameworks, it is suggested to use the above figure (think PHP as an example):

1. ThinkPHP and Workerman are two independent systems, which can be deployed independently (on different servers) and do not interfere with each other.

2. ThinkPHP provides Web page rendering display in browser with HTTP protocol.

3. The js of the page provided by ThinkPHP initiates the websocket connection and connects to the workerman

4. After connecting, a packet (including user name and password or some token string) is sent to Workerman to verify which user the websocket connection belongs to.

5. Call workerman's socket interface to push data only when ThinkPHP needs to push data to the browser.

6. The rest of the requests are still handled according to the HTTP method of ThinkPHP.


As a channel that can push data to browser, Workerman interface can only be called to push data to browser. The business logic is all done in ThinkPHP.

ok, here, run the workerman container. Note that this is CLI mode

Then we play like this in the project receiving information, with the code attached

 // Connect to the server
 var socket = io('');
 // uid can be the user id of its own website to push for uid
 uid = 123;
 // Log in as uid after socket connection
 socket.on('connect', function(){
 socket.emit('login', uid);
 // When the backend pushes a message
 socket.on('new_msg', function(msg){
 console.log("Message received:"+msg);  //Own business logic processing


Next, we add when the user sends information to the user

// Indicates to whom to push. Blank means to push to all online users
 $to_uid = "123";
 // Push url address
 $push_api_url = "";
 $post_data = array(
 "type" => "publish",
 "content" => "data",
 "to" => $to_uid, 
 $ch = curl_init ();
 curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
 curl_setopt ( $ch, CURLOPT_POST, 1 );
 curl_setopt ( $ch, CURLOPT_HEADER, 0 );
 curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
 curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
 curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
 $return = curl_exec ( $ch );
 curl_close ( $ch );


Among them, the implementation of push core code in workerman

// Global array to save uid online data
$uidConnectionMap = array();
// Record the number of online users last broadcast
$last_online_count = 0;
// PHPSocketIO service
$sender_io = new SocketIO(2120);
// When the client initiates a connection event, it sets various event callbacks for the connection socket
// Listen to an http port when $sender GUI is started, through which you can push data to any uid or all UIDs
$sender_io->on('workerStart', function(){
 // Listening to an http port
 $inner_http_worker = new Worker('');
 // Triggered when the http client sends data
 $inner_http_worker->onMessage = function($http_connection, $data){
 global $uidConnectionMap;
 $_POST = $_POST ? $_POST : $_GET;
 // url format of push data type = publish & to = uid & content = XXXX
 case 'publish':
 global $sender_io;
 $to = @$_POST['to'];
 $_POST['content'] = htmlspecialchars(@$_POST['content']);
 // Send data to socket group where uid is specified
 $sender_io->to($to)->emit('new_msg', $_POST['content']);
 // Otherwise push data to all UIDs
 $sender_io->emit('new_msg', @$_POST['content']);
 // http interface returns. If the user is offline, socket returns fail
 if($to && !isset($uidConnectionMap[$to])){
 return $http_connection->send('offline');
 return $http_connection->send('ok');
 return $http_connection->send('fail');


ok, it's done!

For more information, please visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory, as long as you read it to ensure a higher salary (continuous update)

Tags: PHP socket Mobile network

Posted on Mon, 11 May 2020 09:04:41 -0400 by synical21