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

How to build a server with nodejs

Mar 16, 2018 pm 02:23 PM
javascript nodejs server

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);
    });
});
Copy after login
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());
    }
Copy after login
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>
    

        

            

            
                

                                     

                             
        

    

Copy after login
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();
Copy after login
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);
    });
Copy after login

Client:

Establish connection:

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

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();
Copy after login
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
            }));
        }
    }
}
Copy after login

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);
        }
    });
Copy after login
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();
    });
Copy after login
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>
Copy after login
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 " +
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles