How to build a server with nodejs
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
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); }); });
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()); }
WebSocket Echo Demo <script> var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function (e) { console.log('Connection to server opened'); } function sendMessage() { ws.send($('#message').val()); } </script>
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();
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('message', function (message) { var stockRequest = JSON.parse(message);//根据请求过来的数据来更新。 console.log("收到消息", stockRequest); clientStocks = stockRequest['stocks']; sendStockUpdates(ws); });
var ws = new WebSocket("ws://localhost:8181");
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"); } //更新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'); } } // 处理受到的消息 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();
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 })); } } }
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); } });
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(); });
<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>
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 " +
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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.

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

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.

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.

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.

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.

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
