gpt4 book ai didi

http - websocket 消息总是会一次全部到达吗?

转载 作者:行者123 更新时间:2023-12-04 07:56:45 25 4
gpt4 key购买 nike

这个 websockets 教程 https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications有这个例子:

exampleSocket.onmessage = function(event) {
var f = document.getElementById("chatbox").contentDocument;
var text = "";
var msg = JSON.parse(event.data);
var time = new Date(msg.date);
var timeStr = time.toLocaleTimeString();

switch(msg.type) {
case "id":
clientID = msg.id;
setUsername();
break;
case "username":
text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
break;
case "message":
text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
break;
case "rejectusername":
text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
break;
case "userlist":
var ul = "";
for (i=0; i < msg.users.length; i++) {
ul += msg.users[i] + "<br>";
}
document.getElementById("userlistbox").innerHTML = ul;
break;
}

if (text.length) {
f.write(text);
document.getElementById("chatbox").contentWindow.scrollByPages(1);
}
};
它解析从 websockets 服务器接收到的消息。但是,我可以相信由 websocket 服务器发送的 json 总是会立即到达客户端吗?如果它部分到达怎么办?解析它会破坏它。
即使对于非常大的 json 消息,我也可以做出这个假设吗?
我问是因为在 TCP 流上,这是不可能的。消息可能部分到达。
如果无法一次完全接收消息,我怎么知道何时解析 JSON?

最佳答案

是的,每条消息都是作为一个整体接收的。来自 RFC 6455:
1.2.协议(protocol)概述

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. The WebSocket message does not necessarily correspond to a particular network layer framing, as a fragmented message may be coalesced or split by an intermediary.


6.2.接收数据

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/ (comprised of the concatenation of the "Application data" of the fragments) and type /type/ (noted from the first frame of the fragmented message). Subsequent data frames MUST be interpreted as belonging to a new WebSocket message.


https://www.rfc-editor.org/rfc/rfc6455
混淆可能来自术语“套接字”,它是一个低级的原始操作系统 channel ,它以 block 的形式产生数据。但是,WebSocket 是更高级别的协议(protocol)。

关于http - websocket 消息总是会一次全部到达吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66662748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com