gpt4 book ai didi

Javascript:正确全局化 Websocket 发送功能

转载 作者:搜寻专家 更新时间:2023-11-01 04:18:00 26 4
gpt4 key购买 nike

我正在使用 WebSocket 并尝试能够在我的整个应用程序中随时发送套接字数据。当我尝试从另一个函数中访问发送命令时,我收到:

Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.

这只会在我调用函数时发生,这就是我设置 websocket 的方式:

Main.socket = (function() {
var socket = new WebSocket("ws://server:port");

socket.onopen = function() {
console.log("Socket has been opened!");
}

function send() {
socket.send('test');
}

return {
socket: socket,
send: send
}
})();

我能够在全局范围内调用该函数,而且当我从一个函数中使用 console.log Main.socket 时,它能够看到套接字。但是当我调用发送函数时,我得到了那个错误。

最佳答案

这是等待网络套接字连接上线的替代解决方案,将您的调用替换为:

function send() {
web_socket.send('test');
}

用这个:

function send(msg) {

wait_for_socket_connection(socket, function() {
socket.send(msg);
});
};

function wait_for_socket_connection(socket, callback){

setTimeout(
function(){
if (socket.readyState === 1) {
if(callback !== undefined){
callback();
}
return;

} else {

console.log("... waiting for web socket connection to come online");

wait_for_socket_connection(socket,callback);
}
}, 5);
};

关于Javascript:正确全局化 Websocket 发送功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597252/

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