我是react js开发的新手,并尝试将WebSocket集成到我的应用程序中。
但在连接期间发送消息时出错。
我的代码是
const url = `${wsApi}/ws/chat/${localStorage.getItem("sID")}/${id}/`;
const ws = new WebSocket(url);
ws.onopen = (e) => {
console.log("connect");
};
ws.onmessage = (e) => {
const msgRes = JSON.parse(e.data);
setTextMessage(msgRes.type);
// if (msgRes.success === true) {
// setApiMessagesResponse(msgRes);
// }
console.log(msgRes);
};
// apiMessagesList.push(apiMessagesResponse);
// console.log("message response", apiMessagesResponse);
ws.onclose = (e) => {
console.log("disconnect");
};
ws.onerror = (e) => {
console.log("error");
};
const handleSend = () => {
console.log(message);
ws.send(message);
};
得到这个错误
Failed to execute 'send' on 'WebSocket': Still in CONNECTING state
听起来像是在套接字完成连接过程之前调用ws.send
。您需要等待open
事件/回调,或者检查每个文档的readyState
,并在readyState
更改后(即open
回调启动后(对发送进行排队。
不是建议你这样做,但它可能会有所帮助:
const handleSend = () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send()
} else {
// Queue a retry
setTimeout(() => { handleSend() }, 1000)
}
};
正如Logan提到的,我的第一个例子就是懒惰。我只是想让OP解锁,我相信读者足够聪明,能够理解如何从那里获取它。因此,请确保适当地处理可用状态,例如,如果readyState
是WebSocket.CONNECTING
,则注册侦听器:
const handleSend = () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send()
} else if (ws.readyState == WebSocket.CONNECTING) {
// Wait for the open event, maybe do something with promises
// depending on your use case. I believe in you developer!
ws.addEventListener('open', () => handleSend())
} else {
// etc.
}
};
我想只有当ws已经打开时,您才能用它发送数据,并且不检查它何时打开。
基本上,你要求打开,但你在服务器说它打开之前发送了一条消息(这不是即时的,你不知道它需要多少时间;(
我认为你应该添加一个类似let open = false;
的变量
并重写onopen
ws.onopen = (e) => {
open = true;
console.log("connect");
};
然后在你的逻辑中,只有当open等于真正的时,你才能发送消息
不要忘记错误处理;(