Getting list of clients using WebSockets
I'm building a multiuser sketchpad and having some issues getting and keeping an updated list of all the currently connected users. I'm trying to find the best way to notify all existing clients of a new client, and passing the existing clients to the newly connected one. The reason I'm trying to do this is so when one client draws a line, all the other clients find that client in the list, and add the line coords to the respective array.
Server.js
var sys = require("sys");
var ws = require('websocket-server');
var server = ws.createServer({debug: true});
server.addListener("connection", function(conn) {
// When a message is received, broadcast it too all the clients
// that are currently connected.
conn.send('NEW_SERVER_MESSAGE:Welcome!');
conn.send('USER_CONNECTED:' + conn.id);
conn.addListener("message", function( msg ){
switch(msg) {
case 'GET_ALL_ACTIVE_USERS':
server.manager.forEach(function(con) {
conn.broadcast('USER_CONNECTED:' + con.id);
});
break;
case 'UPDATE_CURSOR':
conn.broadcast( msg + '_' + conn.id );
break;
default:
conn.broadcast( msg );
break;
}
});
conn.addListener('close', function( msg ) {
conn.broadcast('USER_DISCONNECTED:' + conn.id);
});
});
server.addListener("error", function(){
console.log(Array.prototype.join.call(arguments, ", "));
});
server.addListener("listening", function(){
console.log("Listening for connections...");
});
server.addListener("disconnected", function(conn){
console.log("<"+conn.id+"> disconnected.");
});
server.listen(8002);</code>
My JS network code:
sketchPadNet = function (b,s) {
var self = this;
this.host = "ws://localhost:8002/server.js";
this.id = null;
this.users = [];
this.heightOffset = 53;
this.scene = s;
this.connected = b;
var User = function(id) {
this.id = id;
this.nickname = id;
this.lines = [];
this.position = "";
};
this.init = function () {
try {
socket = new WebSocket(self.host);
socket.onopen = function (msg) {
socket.send('GET_ALL_ACTIVE_USERS');
};
socket.onmessage = function (msg) {
var m = msg.data.split(':');
switch(m[0]) {
case 'USER_CONNECTED':
console.log('USER_CONNECTED');
var u = new User(m[1]);
u.lines = [];
u.nickname = u.id;
self.users.push(u);
console.log(self.users.length);
console.log(self.users);
break;
case 'USER_DISCONNECTED':
console.log('USER_DISCONNECTED');
for(var i = 0; i < self.users.length; ++i) {
console.log(sel开发者_运维知识库f.users[i]);
if(m[1] == self.users[i].id) {
self.users.splice(i, 1);
}
}
break;
case 'DRAW_LINE':
var tmpMsg = m[1].split('_');
var id = tmpMsg[8];
var userIndex = '';
for(var i = 0; i < self.users.length; ++i) {
if(self.users[i].id == id) userIndex = i;
}
var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2;
var p2 = new BLUR.Vertex3(tmpMsg[3], tmpMsg[4], tmpMsg[5]);
var line = new BLUR.Line3D(p1, p2, tmpMsg[7]);
line.material = tmpMsg[6];
// add the newly created line to the scene.
self.scene.addObject(line);
self.users[userIndex].lines.push(line);
break;
case 'UPDATE_CURSOR':
for(var i = 0; i < self.scene.objects.length; ++i) {
if(self.scene.objects[i].type == 'BLUR.Particle')
self.scene.removeObject(scene.objects[i]);
}
var coords = m[1].split('_');
var id = coords[2];
var userIndex = 0;
for(var i = 0; i < self.users.length; ++i) {
if(self.users[i].id == id)
userIndex = i;
}
self.users[userIndex].position = new BLUR.Vertex3(coords[0], coords[1], 1);
var p = new BLUR.Particle( self.users[userIndex].position, 4 );
p.material = new BLUR.RGBColour(176,23,31,0.3);
self.scene.addObject(p);
break;
case 'RECEIVE_ID':
self.id = m[1];
self.connected.nicknameObj.text = self.id;
console.log(self.id);
break;
break;
}
};
socket.onclose = function (msg) {
// feck!
self.connected.addServerError('Server disconnected, try refreshing.');
};
}
catch (ex) {
console.log('EXCEPTION: ' + ex);
}
};
At the moment, when a new client connected it sends out a message and is added to an array, the the reverse when a client disconnects. For some reason though this isn't staying update? For example when a client draws a line, some of the others report this error:
Uncaught TypeError: Cannot read property 'lines' of undefined
Sorry if i'm being incredibly stupid here, but any help is appreciated!!
Cheers :)
I tried to figure it out by looking at the code but without even a line number on which the error appears, it's pretty hard, anyways.
I suppose this is the problem here:
conn.send('USER_CONNECTED:' + conn.id); // send the connect message to ONE user
conn.broadcast('USER_DISCONNECTED:' + conn.id); // send the disconnect to ALL users
So it seems that you're simply missing a broadcast call when a user connects.
Ok the real issue seems to be in 'DRAW_LINE'
on the client side. Are you sure that you are broadcasting the message to all users and not just sending back the message to the client?
The error points to this line in your client code:
var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2;
Please provide the server code for 'DRAW_LINE'
. The issue is definitely cropping up in there and not in any of the others.
Also, self.users[userIndex]
is undefined
. Maybe that user does not exist?
Why do u need that for loop? Why not just:
if(self.users[id] != undefined) {
var p1 = (self.users[id].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[id].lines[self.users[id].lines.length - 1].point2;
}
I'm trying to find the best way to notify all existing clients of a new client, and passing the existing clients to the newly connected one
I would advice you to have a look at socket.io instead. It can do this easily and fail back to other available transports if websockets aren't supported by the browser.
you might want to consider using an existing server that has things like rooms and user lists built in. for comparison, here's a tutorial for a multiuser sketchpad written in javascript that uses Union Server:
http://www.unionplatform.com/?page_id=2762
and here's Union Server's documented protocol, which includes a description of the messaging system for rooms and clients joining/leaving rooms:
http://unionplatform.com/specs/upc/
might give you some ideas.
colin
精彩评论