Socket.IO发送()不工作

我有一个奇怪的问题。 我正在写一个简单的Socket.IO echo服务器作为一个testing,但我不能让send()方法工作。 在服务器上,我使用这段代码:

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]; }); }); 

send('test')工作正常,但是当我发出echomessage事件时,我没有收到消息。 在服务器或客户端没有错误信息。

所以,在客户端我这样做:

 // 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'); 

但是我根本没有收到这个消息。

我完全不知道我做错了什么。 所有帮助表示赞赏!

我相信你的错误在这里:

  socket.on('addclient', function(id) { socket.id = id; // <-- clients[id] = socket; console.log('New client connected: '+ id); }); 

不要改变socket.id ,因为它是一个内部的,你可能会毁掉使用套接字的内部过程。

它由socket.io自己定义: 来源