首页 > 解决方案 > 使用 socket.ui 向特定房间发送消息不会做任何事情

问题描述

在我的 react 应用程序中,我根据 roomId 参数设置了与特定房间的连接:

componentDidMount() {
    const roomId = window.location.search.replace('?roomId=', '');
    this.setState({ roomId });
    this.socket = io();
    if (!this.socket.socket) {
        this.socket.connect();
    }

    this.socket.on('connect', () => {
        console.log(this.state.roomId);

        this.socket.emit('room', this.state.roomId);
    });

    this.socket.on('message', this.handleMessage)
}

现在在我的 server.js 上,我加入并收听如下消息:

io.on('connection', socket => {
    socket.on('room', function(room) {
        socket.join(room);
    });
    socket.on('message', function(data) {
        socket.to(data.roomId).emit(data);
    });
});

但是当我发送消息时,连接到同一个 roomId 的其他浏览器窗口没有收到任何消息:

const message = {
    roomId: this.state.roomId,
    value: this.state.field,
};
this.socket.emit('message', message);

我监听这样的消息: this.socket.on('message', this.handleMessage)其中 handleMessage 只是用新消息设置状态。

谁能看到为什么不呢?

更新:这里有更多代码可以查看:https ://jsbin.com/pakeyavefo/edit?html,js,output

标签: node.jsreactjsexpresswebsocketsocket.io

解决方案


当你这样做时:

socket.to(data.roomId).emit(data);

您需要同时发送消息名称和一些数据。您没有发送消息名称,因此该事件(如果它甚至被发送)不会匹配客户端上的任何侦听器。也许这应该是:

socket.to(data.roomId).emit('message', data);

推荐阅读