gpt4 book ai didi

javascript - 无法在 'send' : Still in CONNECTING state 上执行 'WebSocket'

转载 作者:行者123 更新时间:2023-12-05 09:32:12 30 4
gpt4 key购买 nike

我是 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 事件/回调,或根据 docs 检查 readyState并在 readyState 更改后排队发送,即在 open 回调触发后。

不建议您这样做,但它可能会有所帮助:

const handleSend = () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send()
} else {
// Queue a retry
setTimeout(() => { handleSend() }, 1000)
}
};

正如 Logan 提到的,我的第一个例子是懒惰的。我只是想让 OP 畅通无阻,我相信读者足够聪明,能够理解如何从那里获取它。因此,请确保适本地处理可用状态,例如,如果 readyStateWebSocket.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.
}
};

关于javascript - 无法在 'send' : Still in CONNECTING state 上执行 'WebSocket',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68303174/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com