If you want to update a list in real time, the traditional approach is to use polling. Take the web as an example, using AJAX to periodically request the server and then get the data displayed on the page. This approach is simple, and the downside is wasting resources.
HTTP1.1 has added support for websocket so that passive displays can be turned into active notifications. That is, through the WebSocket and the server to maintain a persistent link, once the data changes, by the server to notify the client data updates, and then refresh and so on. This eliminates a lot of unwanted 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 () {
console.log ("Socket connection is open");
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);
};
Closes
the connection $ (window) when leaving the page. Bind (' Beforeunload ', function () {
ws.close ();
}
);
This is the realization of a client, but it is far from over. The above code is simply a connection, dialogue, shutdown and other basic actions. If you want to communicate with the server, you must have more specific scenarios. For example, when you receive a message, the type of judgment is further manipulated.
Server: Here, using the Swoole for the WebSocket development of PHP server, 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, installation methods can refer to here: Php installation Swoole extension method
This article first written here, the next will write some more specific operations, interested friends please continue to pay attention to this site. Thank you!