Processing WebSockets messages in order of receiving

前端 未结 2 802
余生分开走
余生分开走 2021-02-19 07:29

Client side part of my application needs to process WebSocket messages in strict order. Unfortunately each message is processed quite long (about 3 seconds), so another appears

相关标签:
2条回答
  • 2021-02-19 08:09

    I think the other answer is wrong. WebSocket IS TCP, which means that the order of delivery is guaranteed. As @Maël Nison quoted, see RFC6455:

    Message fragments MUST be delivered to the recipient in the order sent by the sender

    So you can take it granted that your processing will start in order. However, if you have lots of async callbacks then a later processing may finish before an earlier is still going on. But that's simply wrong implementation (and a bit of callback hell).

    Similar posts:

    • Can websocket messages arrive out-of-order?
    • Websocket: are server data sent synchronously?
    0 讨论(0)
  • 2021-02-19 08:17

    At this time, the WebSocket API in browsers does not expose a frame based or streaming option/API. So there is not really an option to accomplish this natively.

    That means you need to create your own logic / structure within the data packets you're sending from your server to clients. That should be a relatively easy task, I could think of transmitting simpl JSON strings/objects which might have a indexed property on top level.

    {
        packetIndex: 0,
        data: { }
    }
    

    and your client script would need to look into each arriving packet and sort things out correctly (keeping track of arrived packets and "hold + wait" if a packet with a too high indexed arrived)

    0 讨论(0)
提交回复
热议问题