I think the missing piece for you is inside this function: io.sockets.on('connection', function(socket) { ... });
- That function executes every time there is a connection event. And every time that event fires, the 'socket' argument references a brand new socket object, representing the newly connected user. You then need to store that socket object somewhere in a way that you can look it up later, to call either the send or emit method on it, if you need to send messages that will be seen by only that socket.
Here's a quick example that should get you started. (Note: I haven't tested this, nor do I recommend that it's the best way to do what you're trying to do. I just wrote it up in the answer editor to give you an idea of how you could do what you're looking to do)
var allSockets = [];
io.sockets.on('connection', function(socket) {
var userId = allSockets.push(socket);
socket.on('newChatMessage', function(message) {
socket.broadcast.emit('newChatMessage_response', {data: message});
});
socket.on('privateChatMessage', function(message, toId) {
allSockets[toId-1].emit('newPrivateMessage_response', {data: message});
});
socket.broadcast.emit('newUserArrival', 'New user arrived with id of: ' + userId);
});
Edit: If by id you're referring to the id value that socket.io assigns, not a value that you've assigned, you can get a socket with a specific id value using var socket = io.sockets.sockets['1981672396123987'];
(above syntax tested using socket.io v0.7.9)