我有一个奇怪的问题。我正在编写一个简单的 Socket.IO echo 服务器作为测试,但我无法让 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本身定义的:source
关于node.js - Socket.IO send() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335064/