javascript - WebSocket.onmessage 什么时候触发?

标签 javascript websocket

(1) 打开一个WebSocket连接。

var ws = new WebSocket(url);

(2) 建立连接后,发送一条消息,该消息将触发一个 blob 作为响应发回。

ws.onopen = function () {
    ws.send('1000000');
}

(3)onmessage是在响应开始还是响应完成时触发?

ws.onmessage = function () {
    // Has the entire blob arrived or has the download just begun?
}

最佳答案

W3C spec for the WebSocket APImessage应该在“收到 WebSocket 消息时”调度事件:

When a WebSocket message has been received with type type and data data, the user agent must queue a task to follow these steps:

...

  1. Let event be an event that uses the MessageEvent interface, with the event type message, which does not bubble, is not cancelable, and has no default action.

...

  1. Dispatch event at the WebSocket object.

要了解“收到 WebSocket 消息时”的含义,我们必须查阅 RFC 6455, "The WebSocket Protocol" .在 WebSockets 中,参与者发送包含在一个或多个中的消息:

After a successful handshake, clients and servers transfer data back and forth in conceptual units referred to in this specification as "messages". On the wire, a message is composed of one or more frames.

一旦你明白了,你就能明白section 6 of RFC 6455 ,它定义了短语“A WebSocket Message Has Been Received”:

If the frame comprises an unfragmented message (Section 5.4), it is said that _A WebSocket Message Has Been Received_ with type /type/ and data /data/. If the frame is part of a fragmented message, the "Application data" of the subsequent data frames is concatenated to form the /data/. When the last fragment is received as indicated by the FIN bit (frame-fin), it is said that _A WebSocket Message Has Been Received_ with data /data/...

假设服务器端库的 send方法将其参数视为“消息”,规范要求客户端在触发 message 之前等待收到整个消息。事件。

允许流式传输的服务器端 API(例如,它保持消息不完整并保留 FIN 位,直到调用某种 finish 方法)不会导致客户端触发 message事件直到消息结束。

关于javascript - WebSocket.onmessage 什么时候触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532918/

相关文章:

python - WebSocket JWT Token 连接授权

ruby - EventMachine Web 套接字客户端 TLS 连接

golang websocket如何在浏览器意外关闭时得到通知

javascript - 为什么在循环中运行 splice 方法时 JS 数组会跳过某些条目?

javascript - 单击并离开元素时悬停会触发

javascript - 尝试使简单模态示例适应 asp.net 数据列表转发器

jquery - JsSIP 实现

javascript - 使用jQuery动态生成div时如何调用函数

javascript - carouFredSel 将类添加到事件幻灯片

java - Web Socket 上传文件并在同一端点上发送 json