node.js - 使用 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
解决方案
当你这样做时:
socket.to(data.roomId).emit(data);
您需要同时发送消息名称和一些数据。您没有发送消息名称,因此该事件(如果它甚至被发送)不会匹配客户端上的任何侦听器。也许这应该是:
socket.to(data.roomId).emit('message', data);
推荐阅读
- php - 希望php分页迭代器在外部迭代器中过滤项目,而内部迭代器任务将不断传递数据
- javascript - 在 AngularJS 1.x 中查找需要注释的控制器
- arrays - 将表复制到数组并将数组添加到没有标题行vba的表中
- javascript - 什么是 WebSocket 子协议?
- javascript - 如何使我的应用程序启动图标/按钮可添加到 android“快捷方式中心”
- html - 将最后 3 个项目向右移动
- php - 用ajax发送帖子
- php - 使用 postegresql 数据在 Laravel 中加密和解密
- android-management-api - Android Management API /devices 是否有延迟
- python - 使用 MultiIndex 访问 pandas DataFrame 中的单元格会丢失类型信息