[英]How do I know if an message has been sent successfully when using raw WebSocket?
Note that sent != received ... I'm assuming you want to make sure a message was received . 请注意,已发送 !=已接收 ...我假设您要确保已收到消息。
Implement ACK
. 实现
ACK
。 It's super easy and it's the only way I know to make sure the message was received. 这非常简单,这是我知道确保收到消息的唯一方法。
A good enough approach would attach a message ID on the client side and send that ID as part of the message (ie as msgID
in a JSON). 足够好的方法将在客户端附加消息ID,并将该ID作为消息的一部分发送(即,作为JSON中的
msgID
)。 I use a timer ID because I cancel the timer when the ACK arrives and it's a good way to keep the timer data. 我使用计时器ID是因为在ACK到达时我取消了计时器,这是保存计时器数据的好方法。
When the server recognizes a msgID
, it should automatically send an ACK with the same message ID before processing the rest of the message (ie, a JSON for {"event":"ACK", "data":m["msgID"]}
). 服务器识别出
msgID
,应在处理其余消息之前自动发送具有相同消息ID的ACK(即,用于{"event":"ACK", "data":m["msgID"]}
的JSON {"event":"ACK", "data":m["msgID"]}
)。
If you're using binary data, you can simply append a fixed size ID at the beginning of each message (say, 8 bytes), or append a length indicator for a dynamic sized ID. 如果您使用的是二进制数据,则可以简单地在每个消息的开头附加一个固定大小的ID(例如8个字节),或者为动态大小的ID附加一个长度指示符。
EDIT In reflection about Remy's comment: 编辑关于雷米评论的反思:
Yes, using timeout IDs might be relying heavily on the way that the ID "pool" is implemented. 是的,使用超时ID可能在很大程度上取决于实现ID“池”的方式。
A safer design might prefer to avoid assumption by using a counter or some other approach. 更安全的设计可能更喜欢通过使用计数器或其他方法来避免假设。
However, it should also be noted that on all the browsers with which I tested this approach, timeout IDs are always unique. 但是,还应该注意,在我测试过这种方法的所有浏览器中,超时ID始终是唯一的。
On the Mozilla Developer Documentation Site , it states that: 在Mozilla开发人员文档站点上 ,它指出:
It is guaranteed that a timeout ID will never be reused by a subsequent call to setTimeout() or setInterval() on the same object (a window or a worker).
可以确保对同一对象(窗口或工作器)的setTimeout()或setInterval()的后续调用永远不会重用超时ID。 However, different objects use separate pools of IDs.
但是,不同的对象使用单独的ID池。
I think this assumption is correct across the board for all browsers (subject to the ID type overflowing and resetting itself to zero). 我认为这个假设对于所有浏览器都是正确的(取决于ID类型溢出并将其自身重置为零)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.