Based on the combination of HTML5 and Nodejs to realize websocket even if the communication _node.js

Source: Internet
Author: User

Recently have been learning HTML5, do canvas games and so on, found in HTML5 in addition to canvas this powerful tool, there are also websocket is also worth noting. Can be used to do a two-screen interactive game, what is a dual-screen interactive game? is to control the PC-side web game by moving the device. This will be used in real-time communication, and WebSocket is undoubtedly the most appropriate. WebSocket compared to HTTP, there are many advantages, mainly in the WebSocket only to establish a TCP connection, you can actively push data to the client, but also have a more lightweight protocol header, reduce data transfer. So WebSocket is the best protocol for real time communication for the moment.

As for server language choice Nodejs, one is because oneself is to do the front end, to JavaScript is more familiar with, compared with other backstage language, naturally will prefer Nodejs, the second is Nodejs itself event-driven way very good with a large number of clients to maintain high concurrent connection. 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 typing: NPM install nodejs-websocket Carriage can be installed, and then you can start to build the server, Because of the Nodejs-websocket module, so a lot of work do not have to do our own, directly call someone else to encapsulate the good method on the line:

"Server-side code", according to the message from the client to determine which is game1, which is game2, save connection object.

var ws = Require ("Nodejs-websocket");
Console.log ("Start establishing connection ...")
var game1 = Null,game2 = null, Game1ready = False, Game2ready = 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 ("Turn off Connection")
  });
  Conn.on ("Error", function (code, reason) {
    console.log ("abnormally Close")
  })
. Listen (8001)
Console.log ("WebSocket established")

"Game1 Code": by clicking to get the contents of three boxes, upload to the server

<!doctype html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>document</titl
    E> <style> kuang{text-align:center;margin-top:200px;} #mess {text-align:center}. value{width:200px;height:200px;border:1px solid;text-align:center;line-height:200px;
  Display:inline-block;} </style> </head> <body> <div id= "mess" > is connecting ...</div> <div class= "Kuang" > <d IV class= "value" id= "value1" > Ming Mingxiao </div> <div class= "value" id= "value2" > Big chest Big chest </div> <div CLA 
    ss= "value" id= "Value3" > Zhang Xiao Zhang </div> </div> <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 ("Connect server succeeded");
      Ws.send ("game1");
      } ws.onclose = function (e) {console.log ("server shutdown"); } ws.onerror = function () {conSole.log ("Connection error"); } ws.onmessage = function (e) {mess.innerhtml = connection succeeded Document.queryselector (". Kuang"). onclick = Fun
          Ction (e) {var time = new Date ();
        Ws.send (Time + "game1 clicked" "+ e.target.innerhtml+" "); }} </script> </body> </html>

"Game2 Code": Gets the message pushed by the service and displays

<!doctype html>
 
 

Run Screenshots:

The code is very simple: easy to understand, Nodejs-websocket call is very concise, the specific Nodejs-websocket API can be seen https://www.npmjs.org/package/ Nodejs-websocket, there are introductions, their own test, it is very easy, the implementation of the client is also very simple, through the onopen,onmessage and so on several methods can be achieved.

Ps:nodejs Disadvantages

1. Nodejs update quickly, may appear version-compatible
2. The nodejs is not yet ripe, and there is no big production yet.
3. Nodejs Unlike other servers, process and thread operations are not supported for different connections.
While weighing the nodejs to bring us boundless and carefree development, we should consider his immaturity, especially for the "Long Connection" network communication applications.

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.