Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize real-time push based on workerman

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to achieve real-time push based on workerman, I believe that many inexperienced people do not know what to do. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Below by the workerman tutorial column to introduce you to achieve real-time push based on workerman, abandon the method of ajax polling, hope to help friends in need!

Let's start with some of these things:

TCP/IP

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

In the network layer, there are IP protocol, ICMP protocol, ARP protocol, RARP protocol and BOOTP protocol.

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

At the application layer:

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

UDP includes DNS, TFTP and other protocols

Short connection

Connect-> transfer data-> close the connection

HTTP is stateless, and every time the browser and server perform a HTTP operation, a connection is established, but the connection is interrupted at the end of the task.

It can also be said that a short connection refers to the disconnection immediately after the SOCKET connection is sent and the data is received.

Long connection

Connect-> transfer data-> stay connected-> transfer data->. -> close the connection.

Persistent connection means that a SOCKET connection is maintained regardless of whether it is used or not, but the security is poor.

Long connection of http

HTTP can also establish persistent connections, using Connection:keep-alive,HTTP 1.1 for persistent connections by default. The biggest difference between HTTP1.1 and HTTP1.0 is the addition of persistent connection support (which seems to be the specified keep-alive that the latest http1.0 can display), but it is still stateless, or cannot be trusted.

When to use long connection, short connection?

Long connections are mostly used for frequent operations, point-to-point communication, and the number of connections should not be too many. Each TCP connection requires a three-step handshake, which takes time. If each operation is connected first, then the processing speed will be much lower, so it will continue to open after each operation, and the OK will be sent directly during the second processing. There is no need to establish a TCP connection. For example, database connections use long connections, frequent communication with short connections will cause socket errors, and frequent socket creation is also a waste of resources.

Http services like WEB sites generally use short links, because long links will consume certain resources for servers, while thousands or even hundreds of millions of clients with short connections like WEB sites will save some resources. If long links are used, and there are thousands of users at the same time, it can be imagined if each user occupies a connection. Therefore, the amount of concurrency is large, but each user needs to use short connection when there is no need for frequent operation.

What is workerman? Workerman is an open source high-performance PHP socket server framework developed by pure PHP. It is widely used in mobile app, mobile communication, WeChat Mini Programs, mobile game server, online game, PHP chat room, hardware communication, smart home, car Internet, Internet of things and other fields of development. Support TCP persistent connection, support Websocket, HTTP and other protocols, support custom protocols. It has many high performance components, such as asynchronous Mysql, asynchronous Redis, asynchronous Http, asynchronous message queue and so on.

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

Later, it can be implemented in workerman, and the project is also written by tp, according to the official manual.

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

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

2. ThinkPHP provides web pages for rendering and display in browsers based on HTTP protocol.

3. The js of the page provided by ThinkPHP initiates a websocket connection to connect to workerman

4. Send a packet (including user name and password or some token string) to Workerman after connection to verify which user the websocket connection belongs to.

5. Only when ThinkPHP needs to push data to the browser, call the socket API of workerman to push data.

6. The rest of the requests are still called and processed in the HTTP way of the original ThinkPHP.

Summary:

Use Workerman as a channel that can be pushed to the browser, and call the Workerman API to complete the push only when you need to push data to the browser. The business logic is all done in ThinkPHP.

Ok, here, run the workerman container, and notice that this is CLI mode running.

Then do this in the information received by our project, with the code attached.

/ / Connect server var socket = io ('http://127.0.0.1:2120'); / / uid can be the user id of your own website to push uid = 123 for uid; / / log in to socket.on with uid after socket connection (' connect', function () {socket.emit ('login', uid);}) / / socket.on when a message is pushed from the backend ('new_msg', function (msg) {console.log ("received message:" + msg); / / business logic processing})

Next, we add when the user sends a message to the user

/ / indicate to whom to push. Empty means push $to_uid = "123" to all online users; / / url address of the push $push_api_url =" http://127.0.0.1:2121/"; " $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); var_export ($return)

Among them, the implementation of the push core code in workerman

/ / Global array stores uid online data $uidConnectionMap = array (); / / record the number of online users of the last broadcast $last_online_count = 0; / / PHPSocketIO service $sender_io = new SocketIO (2120) / / when the client initiates a connection event, set various event callbacks for the connection socket / / when $sender_io starts, listen to a http port through which you can push data $sender_io- > on ('workerStart', function () {/ / listen to a http port $inner_http_worker = new Worker (' http://0.0.0.0:2121');) to any uid or all uid). / / trigger $inner_http_worker- > onMessage = function ($http_connection, $data) {global $uidConnectionMap; $_ POST = $_ POST? $_ POST: $_ GET; / / url format type=publish&to=uid&content=xxxx switch (@ $_ POST ['type']) {case' publish': global $sender_io for push data when the data is sent by the url client $to = @ $_ POST ['to']; $_ POST [' content'] = htmlspecialchars (@ $_ POST ['content']); / / if there is a specified uid, send data if ($to) {$sender_io- > to ($to)-> emit (' new_msg', $POST ['content']) to the socket group to which uid belongs. / / otherwise push data} else {$sender_io- > emit ('new_msg', @ $_ POST [' content']) to all uid The / / http interface returns if the user's offline socket returns fail if ($to & &! isset ($uidConnectionMap [$to])) {return $http_connection- > send ('offline');} else {return $http_connection- > send (' ok') }} return $http_connection- > send ('fail');};}); if (! defined (' GLOBAL_START')) {Worker::runAll ();}

Ok, it's done!

After reading the above, have you mastered how to implement real-time push based on workerman? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report