我无法让我的 websocket 将数据发送回发送消息的客户端以外的客户端。下面是客户端。
const wss = new WebSocket(`ws://localhost:8080/bru`)
wss.onopen = function(event) {
console.log("open")
setInterval(() => {
wss.send(JSON.stringify(1))
}, 30000);
}
wss.onmessage = (event) => {
if(JSON.parse(event.data)!== 1){
alert(event.data)
}else{
console.log(event.data)
}
};
const handleSubmit = (event) => {
let data = {
participants: global.participants,
message: sendMessage.message,
author: localStorage.getItem("UserId"),
};
wss.send(JSON.stringify(data))
}
下面是使用 express-ws 的服务器端。
router.ws("/bru", function (ws, req) {
console.log("connection made")
ws.onmessage = (event) => {
console.log(event.data)
ws.send(event.data)
}
});
如您所见,我正在将数据从客户端发送到服务器,然后服务器将其发送回客户端.....我如何将其发送回发件人以外的任何客户端?我一直在 Heroku 上对其进行测试,但似乎无法使其正常工作。是不是因为我正在构建的应用程序分为两个应用程序?客户端应用程序是 React 应用程序并通过 cors npm 将其连接到服务器应用程序?
任何提示都会有所帮助。我被困在这个问题上很长时间了。