Based on the combination of html5 and nodejs to implement websocket, even if the communication _ node. js

Source: Internet
Author: User
HTML5 has many notable new features, such as Canvas, local storage, multimedia programming interfaces, WebSocket, and so on. Although everyone is very enthusiastic about it, I personally think it still needs the support of other platforms to truly get started & quot; I 've been learning HTML5 recently, in addition to the powerful canvas tool, WebSocket is also worth noting in HTML5. What is a dual-screen interactive game? PC-side web games are controlled through mobile devices. In this case, real-time communication is necessary, and WebSocket is undoubtedly the most suitable. Compared with HTTP, WebSocket has many advantages, mainly because WebSocket only establishes a TCP connection and can actively push data to the client. In addition, it also has more lightweight protocol headers to reduce the amount of data transferred. Therefore, WebSocket is currently the best protocol for real-time communication.

As for the choice of node. js for the server language, the first reason is that you are a front-end and familiar with javascript. Compared with other background languages, node. JS is naturally preferred, second, the node. js event-driven method is very good at maintaining highly concurrent connections with a large number of clients. So we chose NodeJs.

The implementation of the server is very simple. First install a nodeJs module named nodejs-websocket, and directly input: npm install nodeJs-websocket in the nodejs command line to install it, then we can start to build the server. Because the nodejs-websocket module is available, we don't need to do much work on our own. Simply call the encapsulated methods of others:

Server code: determines which is game1 and game2 Based on the messages sent from the client, and saves the connection object.

Var ws = require ("nodejs-websocket"); console. log ("start to establish a connection... ") var game1 = null, game2 = null, game1Ready = false, game2Ready = false; var server = ws. createServer (function (conn) {conn. on ("text", function (str) {console. log ("received message:" + 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 (" ")});}). listen (8001) console. log ("WebSocket established ")

[Game1 Code]: Click to get the content of the three boxes and upload them to the server.

  
   Document    

Connecting...

James

Big chest

Zhang Xiaozhang

Script var mess = document. getElementById ("mess"); if (window. webSocket) {var ws = new WebSocket ('ws: // 192.168.17.80: 8001 '); ws. onopen = function (e) {console. log ("successfully connected to the server"); ws. send ("game1");} ws. onclose = function (e) {console. log ("server closed");} ws. onerror = function () {console. log ("connection error");} ws. onmessage = function (e) {mess. innerHTML = "connection successful" document. querySelector (". kuang "). onclick = function (e) {var time = new Date (); ws. send (time + "game1 click" "+ e.tar get. innerHTML + ") ;}} script

[Game2 Code]: gets the message pushed by the service and displays

  
   Document    

Script var mess = document. getElementById ("mess"); if (window. webSocket) {var ws = new WebSocket ('ws: // 192.168.17.80: 8001 '); ws. onopen = function (e) {console. log ("successfully connected to the server"); ws. send ("game2");} ws. onclose = function (e) {console. log ("server closed");} ws. onerror = function () {console. log ("connection error");} ws. onmessage = function (e) {var time = new Date (); mess. innerHTML + = time + "message:" + e. data +"
"} Script

Run:

The code is very simple: it is easy to understand, and the call of nodejs-WebSocket is also very simple and clear. For details about the API of nodejs-websocket, refer to the callback.

Ps: nodejs disadvantages

1. nodejs is updated quickly and may be compatible with versions.
2. nodejs is not mature yet, and there is no big production yet.
3. Unlike other servers, nodejs does not support process and thread operations for different connections.
While balancing the infinite and fast development that Nodejs brings to us, we must consider its immaturity, especially for Long-connection network communication applications.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.