node.js - Socket.IO send() 不起作用

标签 node.js socket.io

我有一个奇怪的问题。我正在编写一个简单的 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/

相关文章:

javascript - 如何创建带参数的函数可以传递express.get()方法?

node.js - 如何在不使用 npm start 的情况下在 Cpanel 上启动套接字服务器 (server.js)

node.js - 使用 webrtc + node.js 进行视频 session

安卓 WebView : xhr-polling keeps page 'loading'

javascript - 当 node.js 部署到 Google App Engine 时,socket.io 连接失败

node.js - NodeJS Socket.io Server<-->服务器通信

node.js - 有没有办法从AWS S3到达 "npm install"?

javascript - API 请求适用于 postman,但不适用于 Node.js(请求)

javascript - 在 VS Code 中使用 Node shim 调试 React Native

deployment - 如何使用 npm 在当前目录中安装 package.json 依赖项