storing and retrieving socket
- by Trevor Newhook
From what I can understand, once I create a socket, I can then create an array to store it with
userArray[socket.nickname]=socket;
I can then send a message to it with:
io.sockets.socket(userArray[data.to]).emit('private message', tstamp(), socket.nickname, message);
The basic logic is to store a copy of each socket in an object, identified by nickname. When I want to send a message to that socket, I use the copy of the socket, and send the message via io.sockets.socket(id).emit(). The entire server code is below:
io.sockets.on('connection', function (socket) {
socket.on('user message', function (msg) {
socket.broadcast.emit('user message', tstamp(), socket.nickname, msg);
updateLog('user message', socket.nickname, msg);
});
socket.on('private message', function(data) {
socket.get(data.nickname, function (err, name) {
console.log('Chat message by ', name);
});
updateLog('private message', socket.nickname, data.message);
message=data.message;
io.sockets.socket(userArray[data.to]).emit('private message', tstamp(), socket.nickname, message);
});
socket.on('get log', function () {
updateLog(); // Ensure old entries are cleared out before sending it.
io.sockets.emit('chat log', log);
});
socket.on('nickname', function (nick, fn) {
var i = 1;
var orignick = nick;
while (nicknames[nick]) {
nick = orignick+i;
i++;
}
fn(nick);
nicknames[nick] = socket.nickname = nick;
userArray[socket.nickname]=socket;
socket.set('nickname', nick, function () { socket.emit('ready'); });
socket.broadcast.emit('announcement', nick + ' connected');
// io.sockets.socket(userArray[nick]).emit('newID', 'Your name is: ' + nick, '. Your ID is: '+ userArray[nick]);
io.sockets.emit('nicknames', nicknames);
});