如何处理WebSocket.send错误

时间:2017-10-04 16:17:44

标签: javascript websocket

我正在编写一个Web应用程序 - 认为它是基于WebSocket的聊天。我需要确保用户输入的所有消息都以正确的顺序传递。我不应该丢失任何信息。我不应该两次传递任何信息。

当套接字关闭时,我得到了socket.onclose()回调。但是,当套接字关闭时,可以调用socket.send(),但还没有调用onclose()回调。 socket.send()不返回任何内容,它甚至不会引发onerror()回调。我怎样才能确定socket.send()是否正确发送了消息?

这是我写过的代码。 sendMessage()将消息推送到队列,flush()方法移动所有消息并发送它们。代码安全吗?

        queue: [],
        flush: function() {
            for (;;) {
                if (this.queue.length == 0) break;
                if (this.socket.readyState != 1) break; // *1*
                this.socket.send(this.queue[0]);        // *2*
                if (this.socket.readyState != 1) break; // *3*
                this.queue.shift();
            }
        },
        sendMessage: function(msg) {
            this.queue.push(msg);
            this.flush();
        }

0 个答案:

没有答案