javascript - JavaScript WebSocket.send 方法会阻塞吗?

标签 javascript asynchronous websocket blocking

如果我通过 JavaScript WebSocketsend 方法发送一个大的 BlobArrayBuffer。 .. send 方法调用会阻塞直到发送数据,还是复制数据以异步发送以便调用可以立即返回?

一个相关的(未回答的)问题是,从我的解释来看,一系列快速发送是否会导致 onmessage 事件延迟,正如有人描述的那样发生在 Mobile Safari 中:Apparent blocking behaviour in JavaScript websocket on mobile Safari

最佳答案

根据bufferedAmount属性的描述,我推导出send必须立即返回,因为否则 bufferedAmount 将始终为零。如果它不为零,则必须有来自先前发送调用的缓冲数据,并且如果发送缓冲数据,则没有理由阻止它。

来自 http://dev.w3.org/html5/websockets/

The bufferedAmount attribute must return the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but that, as of the last time the event loop started executing a task, had not yet been transmitted to the network. (This thus includes any text sent during the execution of the current task, regardless of whether the user agent is able to transmit text asynchronously with script execution.) This does not include framing overhead incurred by the protocol, or buffering done by the operating system or network hardware. If the connection is closed, this attribute's value will only increase with each call to the send() method (the number does not reset to zero once the connection closes).

In this simple example, the bufferedAmount attribute is used to ensure that updates are sent either at the rate of one update every 50ms, if the network can handle that rate, or at whatever rate the network can handle, if that is too fast.

var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
    setInterval(function() {
       if (socket.bufferedAmount == 0)
           socket.send(getUpdateData());
    }, 50);
};

The bufferedAmount attribute can also be used to saturate the network without sending the data at a higher rate than the network can handle, though this requires more careful monitoring of the value of the attribute over time.

关于javascript - JavaScript WebSocket.send 方法会阻塞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18246708/

相关文章:

javascript - 从套接字接收消息时 Vue.js 数据不更新

javascript - Websockets 使用 asio c++ 库作为服务器和 javascript 作为客户端

asynchronous - Flutter:使用相同的按钮启动和停止计时器

http - 客户端未使用 websocket 协议(protocol) : 'upgrade' token not found in 'Connection' header

JavaScript,加密.subtle : how to import RSA private key?

javascript - 如何在javascript中将哈希表转换为数组

c# - 将同步包装器放在异步方法上

javascript - 如何在我的项目中编写异步代码

javascript - 如何在angularjs中传递选择选项值

javascript - 访问不常见 JSON 对象中的数据