WebSocket was originally a feature of long links under HTML5 and is currently supported by many browsers.
In the WebSocket protocol, a handshake is first exchanged over HTTP to explicitly upgrade the protocol to WebSocket. A TCP channel is also established to exchange data in frame frames.
In the node environment, the basic functions can be achieved as follows:
First NPM Install Socket.io
1, app.js, initialize Socket.io
var function () { console.log (' Express server listening on port ' + app.get (' Port ');}); var io = require (' Socket.io '). Listen (SRV); server.initserver (IO);
2, Server.js implement server-side code
function (IO) { io.on (' connection ',function(socket) { console.log (' connection '); Socket.on (' disconnect ',function(msg) { console.log (' disconnect '); }); Socket.on (' msg1 ',function(msg) { console.log (msg); Socket.emit (' back ', {key: ' Fredric&sinny '}); });}
3. Client code
<! DOCTYPE html> var socket = io.connect (' http://localhost:3000 '); function sendmsg () { console.log (' Start sendmsg '); Socket.emit (' Msg1 ', {key: ' Fredric '}); Socket.on (' back ',function(msg) { alert (msg.key); }); </script>
The browser-side debug network interface is as follows:
Node (websocket)