【发布时间】:2019-06-06 18:37:54
【问题描述】:
我正在使用带有 React 前端的 node.js。我正在构建基于 GPS 的 MMO 类型的游戏。我最近决定放弃大多数 HTTP 请求并使用套接字,这样我就可以随时发出数据,而前端只需要担心收到数据时如何处理它。
我以前用套接字构建过网站,但从未遇到过这个问题。
基本上,每次我的浏览器打开与节点的套接字连接时,它都会同时打开 2-3 个连接(?)。当它断开连接时,我得到 console.log 说明 3 个套接字连接已关闭。它看起来像这样:
User disconnected
User disconnected
A user has connected to the system with id: nUMbkgX6gleq-JZQAAAD
A user has connected to the system with id: CzFtR2K5NJ1SoiHLAAAE
A user has connected to the system with id: tgGYhpXuOONmL0rMAAAF
目前,这不是问题,但我只是让第一个“库存”发射工作。后来当我再次调用该函数以发出库存时,浏览器似乎没有得到它。但是控制台登录节点功能会正确触发。 我感觉这与多个套接字打开有关。
这里是 React 事件:
this.socket.on("inventory", charData => {
console.log('heres the data', charData)
props.setCharStats(charData[0])
})
Here's the node emitter:
const getCharInventory = (charId, userId) => {
dbInstance
.getCharInventory(charId)
.then(response => {
console.log( // this console.log happens just fine
"emmited inventory, userId is: ", userId, " with this response: ", response)
socket.emit("inventory", response)
})
.catch(err => console.error(err))
}
【问题讨论】:
标签: javascript node.js reactjs websocket socket.io