In the back-end data interaction, we often use Ajax, the use of the traditional HTTP protocol, and the HTTP protocol has a fatal disadvantage is that the request is terminated, the connection is disconnected, we have to maintain this link, we usually use cookies, and since H5 appeared WebSocket, Mother no longer have to worry about my request, can be happy to play, WebSocket is the TCP protocol, so-called "long Connection", can be maintained, the client and the service side of the connection, the interaction is naturally so easily, to happy, the two days use of work, Wrote a chat room based on Nodejs and WebSocket, just to illustrate the principle, did not do any style, do not like to spray
This is the client:
<! DOCTYPE html>
This is the service side:
varWS = Require ("Nodejs-websocket")//Import Nodejs-websocket ModulevarPORT = 3000;varClientcount = 0;//Scream Server Example: "Hi", "Hi!!!"varServer = Ws.createserver (function(conn) {//When a connection is establishedConsole.log ("New connection") Clientcount++; Conn.nickname= ' user ' +clientcount;//each user name varmsg = {}; Msg.type= "Enter";//the type of message,Msg.data = Conn.nickname + ' entered the chat room '; Msg= Json.stringify (msg);//Data FormattingBroadcast (MSG);//for broadcast dataConsole.log (msg); Conn.on ("Text",function(str) {Console.log ("Received" +str)varmsg = {}; Msg.type= ' message '; Msg.data= Conn.nickname + ': ' +str; Msg=json.stringify (msg); Broadcast (MSG); }) Conn.on ("Close",function(Code, reason) {//link off the callback, note that this must be written, otherwise, when the page is closed, the service will throw an exception;Console.log ("Connection closed") varmsg = {}; Msg.type= ' Leave '; Msg.data= Conn.nickname + ' left '; Msg=json.stringify (msg); Broadcast (MSG); }) Conn.on ("Error",function(ERR) {//a callback when an error occurs;Console.log (ERR); }). Listen (PORT);functionBroadcast (str) {Server.connections.forEach (function(connection) {//Traverse all the linksConnection.sendtext (str);//send data to each link });}There's something wrong. Welcome everyone to Spit groove, everyone learn from each other.
WebSocket-built chat room