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.jsCreate 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); }); });
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!