⽤nodejs搭建websocket服务器
简单开始
2.安装ws模块
3.server.js
在项⽬⾥⾯新建⼀个server.js,创建服务,指定8181端⼝,将收到的消息log出来。
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8181 });
<('connection', function (ws) {
console.log('client connected');
<('message', function (message) {
console.log(message);
});
});
4.建⽴⼀个client.html。
在页⾯上建⽴⼀个WebSocket的连接。⽤send⽅法发送消息。
var ws = new WebSocket("ws://localhost:8181");
console.log('Connection to server opened');
}
function sendMessage() {
ws.send($('#message').val());
}
页⾯:
<html xmlns="/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");
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);
nodejs到底是干嘛用的呢var floatChange = randomizedChange / 100;
stocks[symbol] += floatChange;
}
}
var randomMSTime = randomInterval(500, 2500);
stockUpdater = setTimeout(function() {
randomStockUpdater();
}, randomMSTime);
}
randomStockUpdater();
2.连接建⽴之后就开始更新数据
<('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);
<('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() {
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.Fixed(2));
if (newValue < originalValue) {
valElem.addClass('label-danger');
} else if (newValue > originalValue) {
valElem.addClass('label-success');
}
}
// 处理受到的消息
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 (adyState === WebSocket.OPEN) {
clientSocket.send(JSON.stringify({
"type": type,
"id": client_uuid,
"nickname": nickname,
"message": message
}));
}
}
}
3.服务端处理连接
每新增加⼀个连接,都会发送⼀条匿名⽤户的加⼊的提⽰消息,如果消息中带有“/nick” 认为这⼀个修改昵称的消息。然后更新客户端的昵称。其他都会当做聊天消息处
理。
<('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);
<('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);
}
}
};
<('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 = "";
console.log('Connection to server opened');
}
//显⽰
function appendLog(type, nickname, message) {
if (typeof message == "undefined") return;
var messages = ElementById('messages');
var messageElem = ateElement("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 = "<h2>" + preface_label + "  "
+ message + "</h2>";
messageElem.innerHTML = message_text;
messages.appendChild(messageElem);
}
//收到消息处理
var data = JSON.parse(e.data);
nickname = data.nickname;
pe, data.nickname, ssage);
console.log("ID: [%s] = %s", data.id, ssage);
}
appendLog("Connection closed");
console.log("Connection closed");
}
//发送消息
function sendMessage() {
var messageField = ElementById('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);
}
}
运⾏结果:
页⾯关闭之后,连接马上断开。
这种实时响应的体验简直不能太爽,代码也清爽了,前端体验也更好,客户端不⽤⼀直发请求,服务端不⽤等着被轮询。⼩结:上⾯例⼦的代码都很好理解,接下来学习WebSocket协议。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。