WebSocket Study (iii)--build a server with Nodejs

Source: Internet
Author: User
Tags button type live chat install node hasownproperty

The WebSocket API has been learned before, including events, methods, and properties. Details: WebSocket (ii)--API WebSocket is event-driven and supports full-duplex communication. Let's take a look at three simple examples below.

Easy start

1. Install node. https://nodejs.org/en/

2. Installing the WS module

WS: is a websocket library of Nodejs that can be used to create services. Https://github.com/websockets/ws

3.server.js

Create a new server.js in the project, set up a service, specify port 8181, and log the messages you receive.

var websocketserver = require (' ws '). SERVER,WSS = new Websocketserver ({port:8181}); Wss.on (' Connection ', function (WS) {    Console.log (' Client connected ') );    Ws.on (' message ', function (message) {        console.log (message);    });

4. Establish a client.html.

Establish a WebSocket connection on the page. Send a message using the Send method.

var ws = new WebSocket ("ws://localhost:8181");    Ws.onopen = function (e) {        console.log (' Connection to Server opened ');    }    function SendMessage () {        ws.send ($ (' #message '). Val ());    }

Page:

View Code

After running, the server immediately obtains the client's message.

Analog stock

The example above is simple enough to demonstrate how to use Nodejs's WS to create a websocket server. and can accept messages from the client. So the following example shows the real-time update of stocks. Customer Service only need to connect once, the server will continue to send new data, the client to update the UI after the data. Page below, there are five stock, start and stop buttons to test the connection and close.

Service side:

1. Simulate the ups and downs of five stocks.

var stocks = {    "AAPL": 95.0,    "MSFT": 50.0,    "AMZN": 300.0,    "GOOG": 550.0,    "YHOO": 35.0}function Randominterval (min, max) {    return Math.floor (Math.random () * (Max-min + 1) + min);} var Stockupdater;var randomstockupdater = function () {for    (var symbol in stocks) {        if (Stocks.hasownproperty ( Symbol) {            var randomizedchange = Randominterval ( -150, max);            var floatchange = randomizedchange/100;            Stocks[symbol] + = Floatchange;        }    }    var randommstime = Randominterval ($, 2500);    Stockupdater = SetTimeout (function () {        randomstockupdater ();    }, Randommstime);} Randomstockupdater ();

2. Start updating data After the connection is established

Wss.on (' Connection ', function (ws) {    var sendstockupdates = function (ws) {        if (ws.readystate = = 1) {            var stoc Ksobj = {};            for (var i = 0; i < clientstocks.length; i++) {              var symbol = Clientstocks[i];                Stocksobj[symbol] = Stocks[symbol];            }            if (stocksobj.length!== 0) {                ws.send (json.stringify (stocksobj));//The object needs to be converted to a string. WebSocket only supports text and binary data                console.log ("Update", Json.stringify (Stocksobj));    }}} var clientstockupdater = setinterval (function () {        sendstockupdates (WS);    }, +);    Ws.on (' message ', function (message) {        var stockrequest = json.parse (message);//update according to the requested data.        Console.log ("received message", stockrequest);        Clientstocks = stockrequest[' stocks '];        Sendstockupdates (WS);    });

Client:

To establish a connection:

var ws = new WebSocket ("ws://localhost:8181");

OnOpen is only triggered when the connection is successful, and at this point the client needs to send the requested stock to the server.

var isclose = false;    var stocks = {"AAPL": 0, "MSFT": 0, "AMZN": 0, "GOOG": 0, "YHOO": 0};            function Updataui () {Ws.onopen = function (e) {console.log (' Connection to Server opened ');            Isclose = false;            Ws.send (Json.stringify (stock_request));        Console.log ("sened a Mesg"); }//Update UI var changestockentry = function (symbol, OriginalValue, newvalue) {var Valelem = $ (' # ')            + symbol + ' span ');            Valelem.html (newvalue.tofixed (2));                if (NewValue < OriginalValue) {valelem.addclass (' Label-danger ');            Valelem.removeclass (' label-success ');                } else if (NewValue > OriginalValue) {valelem.addclass (' label-success ');            Valelem.removeclass (' Label-danger ');            }}//Processing the received message Ws.onmessage = function (e) {var stocksdata = Json.parse (E.data);  Console.log (Stocksdata);          for (var symbol in stocksdata) {if (Stocksdata.hasownproperty (symbol)) {Chan                    Gestockentry (symbol, Stocks[symbol], Stocksdata[symbol]);                Stocks[symbol] = Stocksdata[symbol];    }            }        }; } updataui ();

The effect is as follows: only need to request once, the data will be constantly updated, the effect is not very good, without polling, nor long connection so troublesome. All the source code is attached at the end of the article.

(The color of the stock and a-shares is reversed, that is, the red and green rise)

Live Chat

The example above is that after the connection is established, the server continuously sends the data to the client. The following example is an example of a simple chat room class. Multiple connections can be established.

1. Install the Node-uuid module, which is used to give each connection a single number.

2. Server-side Message delivery

Message types are notification and messages two, which are informational and chat content. The message also contains an ID, a nickname, and a message content. In the previous section you learned that ReadyState has four values, and open indicates that a connection is established to send a message. If the page is closed, it is websocket.close.

function Wssend (type, Client_uuid, nickname, message) {for    (var i = 0; i < clients.length; i++) {        var Clientso Cket = clients[i].ws;        if (clientsocket.readystate = = = Websocket.open) {            clientsocket.send (json.stringify ({                "type": Type,                "id" : Client_uuid,                "nickname": Nickname,                "message": Message            }));        }}}    

3. Service-Side processing connection

For each new connection, an anonymous user's join message is sent, if the message "/nick" is considered to be the one that modifies the nickname. Then update the client's nickname. Other will be treated as chat messages.

Wss.on (' Connection ', function (ws) {var client_uuid = uuid.v4 ();    var nickname = "Anonymoususer" + clientindex;    Clientindex + = 1;    Clients.push ({"id": Client_uuid, "ws": WS, "nickname": Nickname});    Console.log (' client [%s] connected ', client_uuid);    var connect_message = nickname + "has connected";    Wssend ("Notification", Client_uuid, nickname, Connect_message);    Console.log (' client [%s] connected ', client_uuid); Ws.on (' message ', function (message) {if (Message.indexof ('/nick ') = = = 0) {var nickname_array = message.            Split (');                if (nickname_array.length >= 2) {var old_nickname = nickname;                Nickname = Nickname_array[1];                var nickname_message = "Client" + Old_nickname + "changed to" + nickname;            Wssend ("Nick_update", Client_uuid, nickname, Nickname_message);        }} else {wssend ("message", Client_uuid, nickname, message); }    });

Processing connection shutdown:

  var closesocket = function (custommessage) {for        (var i = 0; i < clients.length; i++) {            if (clients[i].id = = CLI Ent_uuid) {                var disconnect_message;                if (custommessage) {                    disconnect_message = custommessage;                } else {                    disconnect_message = nickname + "has Discon Nected ";                }                Wssend ("Notification", Client_uuid, nickname, Disconnect_message);                Clients.splice (i, 1);}}    ;    Ws.on (' Close ', function () {        closesocket ();    });

4. Client

When not started, the page is as follows and the Change button is used to modify the nickname.

<divclass="Vertical-center"> <divclass="Container"> <ul id="Messages" class="list-unstyled"></ul> "form"Id="Chat_form"onsubmit="sendMessage (); return false;"> <divclass="Form-group"> <inputclass="Form-control"Type="text"Id="message"Name="message"placeholder="Type text to echo in here"Value=""autofocus/> </div> <button type="Button"Id="Send" class="btn Btn-primary"onclick="sendMessage ();">Send Message</button> </form> <divclass="Form-group"><span>nikename:</span><input id="name"Type="text"/> <buttonclass="btn btn-sm btn-info"onclick="changname ();">change</button></div> </div> </div>

Js:

   Establish the connection var ws = new WebSocket ("ws://localhost:8181");        var nickname = "";        Ws.onopen = function (e) {console.log (' Connection to Server opened ');            }//Displays function Appendlog (type, nickname, message) {if (typeof message = = "undefined") return;            var messages = document.getElementById (' Messages ');            var Messageelem = document.createelement ("Li");            var Preface_label;            if (type = = = ' notification ') {Preface_label = "<span class=\" label label-info\ ">*</span>"; } else if (type = = ' Nick_update ') {Preface_label = "<span class=\" label label-warning\ "&GT;*&L            T;/span> "; } else {Preface_label = "<span class=\" label label-success\ ">" + Nickname + "</spa            N> ";            } var message_text = "

Operation Result:

After the page closes, the connection disconnects immediately.

This real-time response experience is simply not too cool, the code is crisp, the front-end experience is better, the client does not have to send requests, the server does not have to wait to be polled.

Summary: The code in the example above is well understood, then learn the WebSocket protocol.

Source: Http://pan.baidu.com/s/1c2FfKbA

Source: Http://pan.baidu.com/s/1o8KRmUQ joined the implementation of the Socket.io.

Api:websocket API

Related: Websoket using protocol Buffers3.0 transmission

This digest from: http://www.cnblogs.com/stoneniqiu/p/5402311.html

Original Stoneniqiu

WebSocket Study (iii)--build a server with Nodejs

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.