我正在使用WebSocket并尝试在整个应用程序中随时发送套接字数据.当我尝试从另一个函数中访问send命令时,我收到:
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.但是当我调用send函数时,我得到了那个错误.
最佳答案
问题是套接字尚未打开.在异步onopen事件发生之前,不能使用WebSocket.send.
虽然使用setTimeout(持续时间足够长)“应该工作”,但处理异步JavaScript编程的正确方法是将程序流视为一系列依赖事件.
在任何情况下,这里有一个小例子,展示了如何使用jQuery Deferred Object(从jQuery 1.8开始,并没有违反Promises/A合同):
Main.socket = (function($) {
var socket = new WebSocket("ws://server:port");
// Promise will be called with one argument,the "send" function for this
// socket.
var readyPromise = $.Deferred();
socket.onopen = function() {
console.log("Socket has been opened!");
readyPromise.resolve(socket.send)
}
return readyPromise;
})(jQuery);
然后,在使用这个小模块的代码中:
Main.socket.then(function (send) {
// This will only be called after `Promise.resolve` is called in the module
// which will be called in the `WebSocket.onopen` callback.
send("Hello world!");
})
// This code may or may not execute before the `then` function above
// depending upon the state the Promise/Deferred Object.
// However,we can get consistent program flow by using `then`-chaining
// of promises.
当然你不必使用Promises – 虽然我更喜欢Promises的统一契约/框架,但回调可以正常工作 – 你可以使用最合适的名称或结构.
另请注意,在整个页面生命周期中使用单个WebSocket可能不太好,因为这将无法正确处理断开连接和恢复方案.