我采用了ping/pong的思路,并且它运行良好。下面是我的server.js文件中的实现:
var SOCKET_CONNECTING = 0;
var SOCKET_OPEN = 1;
var SOCKET_CLOSING = 2;
var SOCKET_CLOSED = 3;
var WebSocketServer = require('ws').Server
wss = new WebSocketServer({ port: 8081 });
wss.broadcast = function broadcast(data,sentBy)
{
for (var i in this.clients)
{
this.clients[i].send(data);
}
};
var userList = [];
var keepAlive = null;
var keepAliveInterval = 5000;
function isJson(str)
{
try {
JSON.parse(str);
}
catch (e) {
return false;
}
return true;
}
wss.on('connection', function connection(ws) {
function ping(client) {
if (ws.readyState === SOCKET_OPEN) {
ws.send('__ping__');
} else {
console.log('Server - connection has been closed for client ' + client);
removeUser(client);
}
}
function removeUser(client) {
console.log('Server - removing user: ' + client)
var found = false;
for (var i = 0; i < userList.length; i++) {
if (userList[i].name === client) {
userList.splice(i, 1);
found = true;
}
}
if (found) {
wss.broadcast(JSON.stringify({userList: userList}));
};
return found;
}
function pong(client) {
console.log('Server - ' + client + ' is still active');
clearTimeout(keepAlive);
setTimeout(function () {
ping(client);
}, keepAliveInterval);
}
ws.on('message', function incoming(message) {
if (isJson(message)) {
var obj = JSON.parse(message);
if (obj.keepAlive !== undefined) {
pong(obj.keepAlive.toLowerCase());
}
if (obj.action === 'join') {
console.log('Server - joining', obj);
ping(obj.name.toLocaleLowerCase());
if (userList.filter(function(e) { return e.name == obj.name.toLowerCase(); }).length <= 0) {
userList.push({name: obj.name.toLowerCase()});
}
wss.broadcast(JSON.stringify({userList: userList}));
console.log('Server - broadcasting user list', userList);
}
}
console.log('Server - received: %s', message.toString());
return false;
});
});
这是我的index.html文件:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Socket Test</title>
</head>
<body>
<div id="loading" style="display: none">
<p align="center">
LOADING...
</p>
</div>
<div id="login">
<p align="center">
<label for="name">Enter Your Name:</label>
<input type="text" id="name" />
<select id="role">
<option value="0">Attendee</option>
<option value="1">Presenter</option>
</select>
<button type="submit" onClick="login(document.getElementById('name').value, document.getElementById('role').value)">
Join
</button>
</p>
</div>
<div id="presentation" style="display: none">
<div class="slides">
<section>Slide 1</section>
<section>Slide 2</section>
</div>
<div id="online" style="font-size: 12px; width: 200px">
<strong>Users Online</strong>
<div id="userList">
</div>
</div>
</div>
<script>
function isJson(str) {
try {
JSON.parse(str);
}
catch (e) {
return false;
}
return true;
}
var ws;
var isChangedByMe = true;
var name = document.getElementById('name').value;
var role = document.getElementById('role').value;
function init()
{
loading = true;
ws = new WebSocket('wss://web-sockets-design1online.c9users.io:8081');
//Connection open event handler
ws.onopen = function(evt)
{
ws.send(JSON.stringify({action: 'connect', name: name, role: role}));
}
ws.onerror = function (msg) {
alert('socket error:' + msg.toString());
}
//if their socket closes unexpectedly, re-establish the connection
ws.onclose = function() {
init();
}
//Event Handler to receive messages from server
ws.onmessage = function(message)
{
console.log('Client - received socket message: '+ message.data.toString());
document.getElementById('loading').style.display = 'none';
if (message.data) {
obj = message.data;
if (obj.userList) {
//remove the current users in the list
userListElement = document.getElementById('userList');
while (userListElement.hasChildNodes()) {
userListElement.removeChild(userListElement.lastChild);
}
//add on the new users to the list
for (var i = 0; i < obj.userList.length; i++) {
var span = document.createElement('span');
span.className = 'user';
span.style.display = 'block';
span.innerHTML = obj.userList[i].name;
userListElement.appendChild(span);
}
}
}
if (message.data === '__ping__') {
ws.send(JSON.stringify({keepAlive: name}));
}
return false;
}
}
function login(userName, userRole) {
if (!userName) {
alert('You must enter a name.');
return false;
}
//set the global variables
name = userName;
role = userRole;
document.getElementById('loading').style.display = 'block';
document.getElementById('presentation').style.display = 'none';
document.getElementById('login').style.display = 'none';
init();
}
</script>
</body>
</html>
如果您想亲自尝试,这里是 Cloud 9 沙盒的链接:https://ide.c9.io/design1online/web-sockets