您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)如何使用nodejs搭建websocket服務(wù)器的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
簡(jiǎn)單開(kāi)始
1.安裝node。https://nodejs.org/en/
2.安裝ws模塊
ws:是nodejs的一個(gè)WebSocket庫(kù),可以用來(lái)創(chuàng)建服務(wù)。 https://github.com/websockets/ws
3.server.js
在項(xiàng)目里面新建一個(gè)server.js,創(chuàng)建服務(wù),指定8181端口,將收到的消息log出來(lái)。
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.建立一個(gè)client.html。
在頁(yè)面上建立一個(gè)WebSocket的連接。用send方法發(fā)送消息。
var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function (e) { console.log('Connection to server opened'); } function sendMessage() { ws.send($('#message').val()); }
頁(yè)面:
<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>
運(yùn)行之后如下,服務(wù)端即時(shí)獲得客戶端的消息。
模擬股票
上面的例子很簡(jiǎn)單,只是為了演示如何運(yùn)用nodejs的ws創(chuàng)建一個(gè)WebSocket服務(wù)器。且可以接受客戶端的消息。那么下面這個(gè)例子演示股票的實(shí)時(shí)更新??头酥恍枰B接一次,服務(wù)器端會(huì)不斷地發(fā)送新數(shù)據(jù),客戶端收數(shù)據(jù)后更新UI.頁(yè)面如下,有五只股票,開(kāi)始和停止按鈕測(cè)試連接和關(guān)閉。
服務(wù)端:
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.連接建立之后就開(kāi)始更新數(shù)據(jù)
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));//需要將對(duì)象轉(zhuǎn)成字符串。WebSocket只支持文本和二進(jìn)制數(shù)據(jù) console.log("更新", JSON.stringify(stocksObj)); } } } var clientStockUpdater = setInterval(function () { sendStockUpdates(ws); }, 1000); ws.on('message', function (message) { var stockRequest = JSON.parse(message);//根據(jù)請(qǐng)求過(guò)來(lái)的數(shù)據(jù)來(lái)更新。 console.log("收到消息", stockRequest); clientStocks = stockRequest['stocks']; sendStockUpdates(ws); });
客戶端:
建立連接:
var ws = new WebSocket("ws://localhost:8181");
onopen直接只有在連接成功后才會(huì)觸發(fā),在這個(gè)時(shí)候?qū)⒖蛻舳诵枰?qǐng)求的股票發(fā)送給服務(wù)端。
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();
運(yùn)行效果如下:只需要請(qǐng)求一次,數(shù)據(jù)就會(huì)不斷的更新,效果是不是很贊,不用輪詢,也不用長(zhǎng)連接那么麻煩了。文章末尾會(huì)附上所有源碼。
(美股的漲跌和A股的顏色是反的,即紅跌綠漲)
實(shí)時(shí)聊天
上面的例子是連接建立之后,服務(wù)端不斷給客戶端發(fā)送數(shù)據(jù)。接下來(lái)例子是一個(gè)簡(jiǎn)單的聊天室類的例子??梢越⒍鄠€(gè)連接。
1.安裝node-uuid模塊,用來(lái)給每個(gè)連接一個(gè)唯一號(hào)。
2.服務(wù)端消息發(fā)送
消息類型分notification和message兩種,前者是提示信息,后者是聊天內(nèi)容。消息還包含一個(gè)id、昵稱和消息內(nèi)容。在上一節(jié)有學(xué)習(xí)到readyState有四個(gè)值,OPEN表示連接建立可以發(fā)送消息。如果頁(yè)面關(guān)閉了,為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.服務(wù)端處理連接
每新增加一個(gè)連接,都會(huì)發(fā)送一條匿名用戶的加入的提示消息,如果消息中帶有“/nick” 認(rèn)為這一個(gè)修改昵稱的消息。然后更新客戶端的昵稱。其他都會(huì)當(dāng)做聊天消息處理。
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); } });
處理連接關(guān)閉:
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.客戶端
沒(méi)有啟動(dòng)時(shí),頁(yè)面如下,change按鈕用來(lái)修改昵稱。
<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"); } //發(fā)送消息 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); } }
運(yùn)行結(jié)果:
頁(yè)面關(guān)閉之后,連接馬上斷開(kāi)。
這種實(shí)時(shí)響應(yīng)的體驗(yàn)簡(jiǎn)直不能太爽,代碼也清爽了,前端體驗(yàn)也更好,客戶端不用一直發(fā)請(qǐng)求,服務(wù)端不用等著被輪詢。
感謝各位的閱讀!關(guān)于“如何使用nodejs搭建websocket服務(wù)器”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。