In order to let the Web side and the server can communicate with each other at any time, before the HTTP has a variety of wording, but now we can use websocket, at least on chrome.
Install Socket.io First
NPM Install Socket.io--save
On the server side, Socket.io and KOA can be combined:
Import Koa from ' Koa ';
Import IO from ' Socket.io '
Let app = new Koa ();
Let server = require (' http '). Server (App.callback ());
Let IO = new io (server);
After the end of all middleware loading in the app,
Io.on (' Connection ', socket=>{
Console.log ("here! Someone connected! ");
Socket.on (' foo ', data=>{
Console.log (data);
SetInterval (() =>socket.emit (' bar ', {text: "HI"}), 1000);
})
});
This way, when a client connects and sends a ' Foo ' event to the server, we send some information to it every 1 seconds.
After the client, establish the connection as follows:
Import io from ' socket.io-client ';
var socket = new Io ("http://localhost:3000");
Socket.on (' Connect ', () =>{
Console.log ("connected!");
})
Socket.on (' Disconnect ', () =>{
Console.log ("disconnected!");
})
Then send and accept events from the server just now.
Socket.emit ("foo", {});
Socket.on ("Bar", data=>{
Console.log ("Rec:", data);
})
You can see in the console in chrome that every second of the Web is receiving information from the server, but WebSocket seems to support it on other browsers.
TCG Development Log (3) Socket.io