This article mainly introduces PHP using Swoole real-time update client data related information, the need for friends can refer to. We hope to help you.
If you want to update a list in real time, the traditional approach is to use a polling method. Take the web as an example, through Ajax timed request server and then get the data displayed on the page. This approach is simple, and the downside is wasting resources.
HTTP1.1 adds support for websocket so that the passive display can be turned into an active notification. That is, through the WebSocket and the server to maintain a persistent link, once the data changes, the server notifies the client that the data is updated, and then refresh, and so on. This eliminates a lot of unnecessary passive requests and saves server resources.
To implement a Webscoket program, you first need to use a browser that supports HTML5
if (ws = = = null) {var wsserver = ' ws://' + location.hostname + ': 8888 '; ws = new WebSocket (wsserver); ws.onopen = function () {con Sole.log ("Socket connection is open");}; Ws.onmessage = function (e) {console.log ("message:" + E.data);}; Ws.onclose = function () {Console.log ("socket Disconnected");}; Ws.onerror = function (e) {Console.log ("ERROR:" + e.data);};/ /Close Connection $ (window) When you leave the page. Bind (' Beforeunload ', function () {ws.close ();});}
This achieves a client, but it is far from over. The above code is simply the basic action of connecting, talking, and closing. If you want to communicate with the server, you must have a more specific plan. For example, when a message is received to determine the type for further operation.
Server: Swoole is used here for PHP server websocket development, using Swoole for PHP websocket development is very simple, and it also supports httpserver support.
$server = new Swoole_websocket_server ("0.0.0.0", 8888), $server->on (' Open ', function (Swoole_websocket_server $ Server, $request) {echo "Server:handshake success with fd{$request->fd}\n";}); $server->on (' message ', function (Swoole_websocket_server $server, $frame) {echo "receive from {$frame->fd}:{$ frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n "; $server->push ($frame->fd," This is (server ");}); $server->on (' Close ', function ($ser, $FD) {echo "Client {$FD} closed\n";}); $server->start ();
Swoole is an extension of PHP, the installation method can be referenced here: PHP installation Swoole extension method
Related recommendations:
THINKPHP5 and Swoole An instance of using SMTP to implement asynchronous bulk mail
Swoole Development Essentials Introduction
PHP Asynchronous multithreaded Swoole Usage example