如果我通过 JavaScript WebSocket
的 send
方法发送一个大的 Blob
或 ArrayBuffer
。 .. 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/