Real-time data communication synchronization based on WebSocket for WebGL 3D topology (i)

Source: Internet
Author: User
Tags emit node server

Today there is no continuation of the previous story, interspersed with a small episode, WebSocket real-time data communication synchronization problem, today we are not very pure WebSocket related knowledge, we use the WebGL 3D topology map to present an interesting Demo. Let's take a look at what this real-time data communication is all about.

Let's talk about the idea of the Demo, first I want to have a 3D topology diagram component, create several nodes above, and then through the pull layout (forcelayout) to the automatic layout of these nodes, but there is a certain, need to be in a different page window, The location of the corresponding node is the same, simply said that the different page window is the same node layout, and drag the different pages in the window of any node, will update all the page window, so that all the window rendering is the same.

According to the above idea, how should we plan? Now that you need real-time data communication, what do you need to use Websocket,websocket? WebSocket is HTML5 a new protocol, it does not have a standard API, each implementation has its own set of APIs, where we do not go into detail WebSocket concrete implementation, I can not speak, at least not now.

Here we use the more accessible node. JS's Socket.io to do the communication framework,Socket.io to make long-connected communication is very simple, the server can no longer wait for the client's request to send a message directly to the client, According to this characteristic, the data communication synchronization problem can be realized.

Let's write a simple example of sending any client message to the server intact and forwarding it to all clients connected to the server, and we'll look at how to implement a feature like this, and how to design the service side.

First we have to build a simple Web server.

var app = require (' Express ') (); var http = require (' http '). Server (app); App.get (function(req, res) {    res.end (' );}); Http.listen (function() {    console.log (' listening on *:4000 ');});

The above code of the node. JS code, paste this string of code into a JS file, such as named Server.js and then in Terminal CD to server.js corresponding folder, if Node server.js back, if found to report the Can Not find module ' xxx ', then you do not have the relevant package for the installation program in the current directory. Then we create a file called Package.json in the current directory, then copy the following program to the file, and then enter the NPM install in the Terminal, and so on after the installation, you can start the server normally.

{  "name": "Socket-example",  "version": "0.0.1",  "description": "My first Socket.io app ",  " dependencies ": {    " Express ":" ^4.10.2 ",    " Socket.io ":" ^ 1.4.8 "  }}

After booting, you can see Hello message! by typing localhost:4000 on the browser The words. This is the simplest HTTP server, so how do we add WebSocket functionality to it? Sharp-eyed's classmates may have found that the above Package.json content already contains Socket.io, then Socket.io How to use it, how to achieve real-time data communication effect?

var io = require (' Socket.io ') (HTTP), Io.on (function(socket) {    Console.log (' A user connected ');    Socket.on (function() {        console.log (' user disconnected ');    });    Socket.on (function(msg) {        io.emit (' message ', msg);    } );

By adding the above code in Server.js, you can implement real-time data communication between clients. But in the browser input localhost:4000 what you see is Hello message! , how do you get access to specific HTML page content? At this point, we need to modify our server a little bit.

function (req, res) {    + '/index.html ');});

That is the Res.end ('

So how does the client implement to show real-time communication on the server?

<!DOCTYPE HTML><HTML>    <Head>        <MetaCharSet= "Utf-8">        <title>Socket.io Message</title>        <styleMedia= "Screen">#send{font-size:14px; }#msgList{List-style-type:None;margin:10px 0px;padding:0; }#msgList Li{padding:5px 10px; }#msgList li:nth-child (odd){background:#eee; }        </style>        <Scriptsrc= "/socket.io/socket.io.js"></Script>        <Script>            varSocket=io (); varInit= function() {                varinput=document.getElementById ('message'), Sendfunc= function() {                        varmsg=Input.value; if (!msg)return; Socket.emit ('message', Input.value); Input.value= "';                }; Input.addeventlistener ('KeyUp', function(e) {if(E.keycode===  -) {sendfunc ();                }                }); varList=document.getElementById ('msglist'); Socket.on ('message', function(msg) {varLi=Document.createelement ('Li'); Li.innerhtml=msg; List.insertbefore (Li, list.childnodes[0]);                }); varbtn=document.getElementById ('Send'); Btn.addeventlistener ('Click', Sendfunc);        }; </Script>    </Head>    <Bodyonload= "init ();">Message:<inputID= "message" />        <Buttontype= "button"ID= "Send">Send</Button><BR/>        <ulID= "Msglist"></ul>    </Body></HTML>

The above code can be done to synchronize the data, specifically I will explain.

The page is simple, has an input text box, and a Send button, there is a UL unordered list to display the content sent by the user, when the user enters the input text box, press Enter or click the Send button will want the server to send the text box fill in the content, and the server This message will be pushed to all the clients intact, after the client receives the message, it will want to fill in the UL unordered list of messages.

This Demo is more than I can tell on this http://socket.io/get-started/chat/ , and you will be able to read it in detail and understand it more comprehensively.

Because of the length of the problem, I heaven introduced here, Next, we will focus on the above mentioned in conjunction with the HT for Web 3D topology diagram component to show the effect of real-time data communication, so that each client synchronous operation.

Real-time data communication synchronization based on WebSocket for WebGL 3D topology (i)

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.