Disclaimer: This article is original article, if need reprint, please indicate source waxes, thank you!
Recently are learning HTML5, do canvas games and so on, found that HTML5 in addition to canvas this powerful tool, there are websocket is also worth noting. Can be used to do two-screen interactive game, what is a two-screen interactive game? is to control PC-side web games through mobile devices. This will use real-time communication, and WebSocket is undoubtedly the most appropriate. WebSocket compared to HTTP, there are many advantages, mainly manifested in WebSocket only establish a TCP connection, you can actively push the data to the client, but also a more lightweight protocol header, reduce the amount of data transfer. So WebSocket is the best protocol for real-time communication for the moment.
As for the server language selection Nodejs, one is to do the front-end, the JavaScript is more familiar with, compared to other background language, will naturally prefer Nodejs, and the other is Nodejs itself event-driven way is good at maintaining high concurrent connections with a large number of clients. So I chose Nodejs.
The implementation of the server is very simple, first installed a Nodejs module, called Nodejs-websocket, directly in the Nodejs command line-typed: npm install Nodejs-websocket Enter can be installed, and then you can start to build the server, Because of the Nodejs-websocket module, so a lot of work does not have to do with our own, directly call someone else packaged method is OK:
"Server Code", according to the message from the client to determine which is game1, which is game2, save the Connection object.
var ws = Require ("Nodejs-websocket"), Console.log ("Start establishing connection ...") var game1 = Null,game2 = null, Game1ready = False, Game2rea DY = False;var Server = ws.createserver (function (conn) { Conn.on ("Text", function (str) { Console.log ("The message Received is:" +STR) if (str=== "Game1") { game1 = conn; Game1ready = true; Conn.sendtext ("Success"); } if (str=== "Game2") { game2 = conn; Game2ready = true; } if (game1ready&&game2ready) { game2.sendtext (str); } Conn.sendtext (str) }) Conn.on ("Close", function (code, reason) { console.log ("Close Connection") }); Conn.on ("Error", function (code, reason) { console.log ("abnormal Close") }). Listen (8001) Console.log ("WebSocket established")
"Game1 Code": Click to get three boxes of content, upload to the server
<!doctype html> Game2 code: Gets the message that is pushed by the service and displays the
<!doctype html>The code is very simple: it is easy to understand, Nodejs-websocket call is very concise and clear, the specific Nodejs-websocket API can see https://www.npmjs.org/package/ Nodejs-websocket, there are introduced, their own test, it is easy, the implementation of the client is very simple, through the onopen,onmessage and other methods can be achieved.
Html5+nodejs for WebSocket Instant Messaging