This article describes how to use php + swoole to Update client data in real time (1). If you want to update a list in real time, the traditional method is round robin. Take the web as an example. Use Ajax to regularly request the server and then obtain the data displayed on the page. This method is simple, but the disadvantage is that it is a waste of resources.
HTTP1.1 adds support for websocket so that passive display can be changed to active notification. That is to say, the websocket is used to maintain a persistent link with the server. Once the data changes, the server notifies the client that the data has been updated, and then refresh the data. This saves a lot of unnecessary passive requests and server resources.
To implement a webscoket program, you must first use a browser that supports html5.
If (ws = null) {var wsServer = 'ws: // '+ location. hostname + ': 8888'; ws = new WebSocket (wsServer); ws. onopen = function () {console. log ("socket connection enabled") ;}; ws. onmessage = function (e) {console. log ("message:" + e. data) ;}; ws. onclose = function () {console. log ("socket connection disconnected") ;}; ws. onerror = function (e) {console. log ("ERROR:" + e. data) ;}; // close the connection when you leave the page $ (window ). bind ('beforeunload', function () {ws. close ();});}
In this way, a client is implemented, but the process is far from over. The above code is just a simple connection, dialog, close, and other basic actions. If you want to communicate with the server, you must have a more specific solution. For example, when a message is received, the system determines the type for further operations.
Server: Swoole is used for websocket development on the php server. It is very simple to use swoole for websocket development on the php server, and it also supports httpserver.
$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. For the installation method, refer to: Install swoole extension in php
This article is written here first, and the next article will write more specific operations. If you are interested, please continue to pay attention to this site. Thank you!