Home >Web Front-end >JS Tutorial >How to build a server with nodejs

How to build a server with nodejs

php中世界最好的语言
php中世界最好的语言Original
2018-03-16 14:23:365175browse

This time I will show you how to build a server with nodejs, and what are the precautions for building a server with nodejs. The following is a practical case, let's take a look.

Recommended tutorials on php Chinese website: Node.js video tutorial

Easy start

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

2. Install ws module

ws: It 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, create the service, and specify Port 8181, log the received messages.

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. Create a client.html.

Establish a WebSocket connection on the page. Use the send method

to send a message .

 var ws = new WebSocket("ws://localhost:8181");
    ws.onopen = function (e) {
        console.log('Connection to server opened');
    }    function sendMessage() {
        ws.send($('#message').val());
    }
Page:


    
    WebSocket Echo Demo
    
    
    
    
    
    <script>
    var ws = new WebSocket(&quot;ws://localhost:8181&quot;);
    ws.onopen = function (e) {
        console.log('Connection to server opened');
    }    function sendMessage() {
        ws.send($('#message').val());
    }    </script>
    

        

            

            
                

                                     

                             
        

    

View Code

After running as follows, the server will get the client’s message immediately.

Simulated Stocks

The above example is very simple, just to demonstrate how to create a WebSocket server using nodejs's ws. And can accept messages from clients. So the following example demonstrates real-time updates of stocks. The client only needs to connect once, the server will continuously send new data, and the client will update the UI after receiving the data. The page is as follows, there are five stocks, and the start and stop buttons test the connection and close.

Server:

1. Simulate the rise and fall 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, 150);            var floatChange = randomizedChange / 100;
            stocks[symbol] += floatChange;
        }
    }    var randomMSTime = randomInterval(500, 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 stocksObj = {};            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));//需要将对象转成字符串。WebSocket只支持文本和二进制数据
                console.log("更新", JSON.stringify(stocksObj));
            }
           
        }
    }    var clientStockUpdater = setInterval(function () {
        sendStockUpdates(ws);
    }, 1000);
    ws.on(&#39;message&#39;, function (message) {        var stockRequest = JSON.parse(message);//根据请求过来的数据来更新。
        console.log("收到消息", stockRequest);
        clientStocks = stockRequest[&#39;stocks&#39;];
        sendStockUpdates(ws);
    });

Client:

Establish connection:

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

onopen directly only after the connection is successful will be triggered. At this time, the stocks that the client needs to request are sent 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(&#39;Connection to server opened&#39;);
            isClose = false;            ws.send(JSON.stringify(stock_request));
            console.log("sened a mesg");
        }        //更新UI
        var changeStockEntry = function (symbol, originalValue, newValue) {            var valElem = $(&#39;#&#39; + symbol + &#39; span&#39;);
            valElem.html(newValue.toFixed(2));            if (newValue < originalValue) {
                valElem.addClass(&#39;label-danger&#39;);
                valElem.removeClass(&#39;label-success&#39;);
            } else if (newValue > originalValue) {
                valElem.addClass('label-success');
                valElem.removeClass('label-danger');
            }
        }        // 处理受到的消息
        ws.onmessage = function (e) {            var stocksData = JSON.parse(e.data);
            console.log(stocksData);            for (var symbol in stocksData) {                if (stocksData.hasOwnProperty(symbol)) {
                    changeStockEntry(symbol, stocks[symbol], stocksData[symbol]);
                    stocks[symbol] = stocksData[symbol];
                }
            }
        };
    }
    updataUI();
The operation effect is as follows: you only need to request it once, and the data will be continuously updated. Isn’t the effect great? There is no need for polling, and there is no need for the trouble of long connections. All source code will be attached at the end of the article.

(The rise and fall of U.S. stocks is the opposite of the color of A-shares, that is, red falls and green rises)

Live chat

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

1. Install the node-uuid module to give each connection a unique number.

2. Server-side message sending

There are two message types: notification and message. The former is prompt information, and the latter is chat content. The message also contains an id, nickname and message content. In the previous section, we learned that readyState has four values. OPEN indicates that the connection is established and messages can be sent. 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 clientSocket = clients[i].ws;        if (clientSocket.readyState === WebSocket.OPEN) {
            clientSocket.send(JSON.stringify({                "type": type,                "id": client_uuid,                "nickname": nickname,                "message": message
            }));
        }
    }
}

3. The server handles the connection

Every time a new connection is added, a prompt message for the anonymous user to join will be sent. If the message contains "/nick", it is considered that this one changes the nickname. news. Then update the client's nickname. Others will be treated as chat messages.

wss.on(&#39;connection&#39;, function(ws) {    var client_uuid = uuid.v4();    var nickname = "AnonymousUser" + clientIndex;
    clientIndex += 1;
    clients.push({ "id": client_uuid, "ws": ws, "nickname": nickname });
    console.log(&#39;client [%s] connected&#39;, client_uuid);    var connect_message = nickname + " has connected";    wsSend("notification", client_uuid, nickname, connect_message);
    console.log(&#39;client [%s] connected&#39;, client_uuid);
    ws.on(&#39;message&#39;, function(message) {        if (message.indexOf(&#39;/nick&#39;) === 0) {            var nickname_array = message.split(&#39; &#39;);            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 closure:

  var closeSocket = function(customMessage) {        for (var i = 0; i < clients.length; i++) {            if (clients[i].id == client_uuid) {                var disconnect_message;                if (customMessage) {
                    disconnect_message = customMessage;
                } else {
                    disconnect_message = nickname + " has disconnected";
                }                wsSend("notification", client_uuid, nickname, disconnect_message);
                clients.splice(i, 1);
            }
        }
    };
    ws.on('close', function () {
        closeSocket();
    });
4. When the client

is not started, the page is as follows. The change button is used to modify the nickname.

<p class="vertical-center">
        <p class="container">
            <ul id="messages" class="list-unstyled"></ul>
            <hr/>
            <form role="form" id="chat_form" onsubmit="sendMessage(); return false;">
                <p class="form-group">
                    <input class="form-control" type="text" id="message" name="message"
                           placeholder="Type text to echo in here" value="" autofocus/>
                </p>
                <button type="button" id="send" class="btn btn-primary"
                        onclick="sendMessage();">
                    Send Message                </button>
            </form>
            <p class="form-group"><span>nikename:</span><input id="name" type="text" /> <button class="btn btn-sm btn-info" onclick="changName();">change</button></p>
        </p>
    </p>
View Code

js:

   
         ws =  WebSocket("ws://localhost:8181" nickname = ""= 'Connection to server opened'
         ( message == "undefined")  messages = document.getElementById('messages' messageElem = document.createElement("li" (type === 'notification'= "<span class=\"label label-info\">*</span>"  (type == 'nick_update'= "<span class=\"label label-warning\">*</span>"= "<span class=\"label label-success\">"
                + nickname + "</span>" message_text = "<h2>" + preface_label + "  "
            + message + "</h2>"=
        ws.onmessage =  data =="ID: [%s] = %s"= "Connection closed""Connection closed"
         messageField = document.getElementById('message' (ws.readyState ==== ''
         name = $("#name" (ws.readyState ==="/nick " +
Running results:

After the page is closed, the connection is immediately disconnected .

This kind of real-time response experience is simply amazing, the code is cleaner, and the front-end experience is better. The client does not have to send requests all the time, and the server does not have to wait to be polled.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

JavaScript’s var and this, {} and function

How to deploy Node.JS to Heroku

The above is the detailed content of How to build a server with nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn