确定websocket send()是否完成

dus*_*n.b 5 javascript websocket

如果确定send()已经完成,有没有办法得到通知?因为我注意到send()函数没有阻塞,代码连续.有没有一种简单的方法可以阻止它或在发送完成时以某种方式通知?

小智 5

你可以依靠 Socket.bufferedamount (从未尝试过)

http://www.whatwg.org/specs/web-apps/current-work/multipage/network.html#dom-websocket-bufferedamount

var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
    setInterval(function() {
        if (socket.bufferedAmount == 0){
          // Im' not busy anymore - set a flag or something like that
        }
    }, 50);
};
Run Code Online (Sandbox Code Playgroud)

或者为每个客户端消息实现来自服务器的确认应答(尝试过,工作正常)