I have a weird issue. I'm writing a simple Socket.IO echo server as a test, but I can't get the send() method to work. On the server I'm using this piece of code:
var io = require('socket.io').listen(3000);
var clients = {};
io.sockets.on('connection', function (socket) {
socket.send('test');
socket.on('addclient', function(id) {
socket.id = id;
clients[id] = socket;
console.log('New client connected: '+ id);
});
socket.on('echomessage', function(message) {
console.log('Sending echo message to client '+ socket.id);
socket.send(message);
});
socket.on('disconnect', function() {
console.log('Client '+ socket.id + ' disconnected');
delete clients[socket.id];
});
});
The send('test') is working perfectly, but when I emit the echomessage event, I don't receive the message. No error messages at all on the server or client side.
So, on the clientside I do this:
// Connect with the server (works, connection established)
// works too, I see it on the server
sock.emit('addclient', 1);
// I see 'Sending echo message to client 1' on the server
sock.emit('echomessage', 'Echo this please');
But I don't receive the message at all.
I have absolutely no clue of what I'm doing wrong. All help is appreciated!
I believe your error is somewhere here :
socket.on('addclient', function(id) {
socket.id = id; // <--
clients[id] = socket;
console.log('New client connected: '+ id);
});
Don't change socket.id
, because it is an internal, and you might ruin the internal process of using a socket.
It is defined by socket.io itself : source