您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關如何使用nodejs搭建websocket服務器的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
簡單開始
1.安裝node。https://nodejs.org/en/
2.安裝ws模塊
ws:是nodejs的一個WebSocket庫,可以用來創建服務。 https://github.com/websockets/ws
3.server.js
在項目里面新建一個server.js,創建服務,指定8181端口,將收到的消息log出來。
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.建立一個client.html。
在頁面上建立一個WebSocket的連接。用send方法發送消息。
var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function (e) { console.log('Connection to server opened'); } function sendMessage() { ws.send($('#message').val()); }
頁面:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>WebSocket Echo Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link href="../bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <script src="../js/jquery-1.12.3.min.js"></script> <script src="../js/jquery-1.12.3.min.js"></script> <script src="../bootstrap-3.3.5/js/bootstrap.min.js"></script> <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> </head> <body > <div class="vertical-center"> <div class="container"> <p> </p> <form role="form" id="chat_form" onsubmit="sendMessage(); return false;"> <div class="form-group"> <input class="form-control" type="text" name="message" id="message" placeholder="Type text to echo in here" value="" /> </div> <button type="button" id="send" class="btn btn-primary" onclick="sendMessage();"> Send! </button> </form> </div> </div> </body> </html>
運行之后如下,服務端即時獲得客戶端的消息。
模擬股票
上面的例子很簡單,只是為了演示如何運用nodejs的ws創建一個WebSocket服務器。且可以接受客戶端的消息。那么下面這個例子演示股票的實時更新。客服端只需要連接一次,服務器端會不斷地發送新數據,客戶端收數據后更新UI.頁面如下,有五只股票,開始和停止按鈕測試連接和關閉。
服務端:
1.模擬五只股票的漲跌。
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.連接建立之后就開始更新數據
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");
onopen直接只有在連接成功后才會觸發,在這個時候將客戶端需要請求的股票發送給服務端。
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();
運行效果如下:只需要請求一次,數據就會不斷的更新,效果是不是很贊,不用輪詢,也不用長連接那么麻煩了。文章末尾會附上所有源碼。
(美股的漲跌和A股的顏色是反的,即紅跌綠漲)
實時聊天
上面的例子是連接建立之后,服務端不斷給客戶端發送數據。接下來例子是一個簡單的聊天室類的例子。可以建立多個連接。
1.安裝node-uuid模塊,用來給每個連接一個唯一號。
2.服務端消息發送
消息類型分notification和message兩種,前者是提示信息,后者是聊天內容。消息還包含一個id、昵稱和消息內容。在上一節有學習到readyState有四個值,OPEN表示連接建立可以發送消息。如果頁面關閉了,為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.服務端處理連接
每新增加一個連接,都會發送一條匿名用戶的加入的提示消息,如果消息中帶有“/nick” 認為這一個修改昵稱的消息。然后更新客戶端的昵稱。其他都會當做聊天消息處理。
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(); });
4.客戶端
沒有啟動時,頁面如下,change按鈕用來修改昵稱。
<div class="vertical-center"> <div class="container"> <ul id="messages" class="list-unstyled"></ul> <hr/> <form role="form" id="chat_form" onsubmit="sendMessage(); return false;"> <div class="form-group"> <input class="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> <div class="form-group"><span>nikename:</span><input id="name" type="text" /> <button class="btn btn-sm btn-info" onclick="changName();">change</button></div> </div> </div>
js:
//建立連接 var ws = new WebSocket("ws://localhost:8181"); var nickname = ""; ws.onopen = function (e) { console.log('Connection to server opened'); } //顯示 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\">*</span>"; } else { preface_label = "<span class=\"label label-success\">" + nickname + "</span>"; } var message_text = "<h3>" + preface_label + " " + message + "</h3>"; messageElem.innerHTML = message_text; messages.appendChild(messageElem); } //收到消息處理 ws.onmessage = function (e) { var data = JSON.parse(e.data); nickname = data.nickname; appendLog(data.type, data.nickname, data.message); console.log("ID: [%s] = %s", data.id, data.message); } ws.onclose = function (e) { appendLog("Connection closed"); console.log("Connection closed"); } //發送消息 function sendMessage() { var messageField = document.getElementById('message'); if (ws.readyState === WebSocket.OPEN) { ws.send(messageField.value); } messageField.value = ''; messageField.focus(); } //修改名稱 function changName() { var name = $("#name").val(); if (ws.readyState === WebSocket.OPEN) { ws.send("/nick " + name); } }
運行結果:
頁面關閉之后,連接馬上斷開。
這種實時響應的體驗簡直不能太爽,代碼也清爽了,前端體驗也更好,客戶端不用一直發請求,服務端不用等著被輪詢。
感謝各位的閱讀!關于“如何使用nodejs搭建websocket服務器”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。