6

When using a WebSocket full-duplex data connection between a client and a server, am I guaranteed, when sending two messages from the server, that I will receive those two exact same messages on the client, something TCP does not ?

In other words, if the server sends in turn hello and then its me, does the client always receive two messages containing hello and its me or is it possible the client receives helloit and then s me or even one only message like helloits me ?

JanR
  • 6,052
  • 3
  • 23
  • 30
Magix
  • 4,989
  • 7
  • 26
  • 50
  • Have a look at this post: http://stackoverflow.com/questions/20685208/websocket-transport-reliability-socket-io-data-loss-during-reconnection – JanR Mar 11 '16 at 02:12
  • there are delimiters around each message; they will never be combined like that. I'm not sure what "guaranteed" means to you; the spec is written a certain way and lost packets are re-sent, unlike a datagram, but it is the internet and without a follow-back verification it's hard to determine if a client got a particular message or not from the high-level socket APIs we use from JS. – dandavis Mar 11 '16 at 03:03

2 Answers2

5

WebSocket originally had text message start and finish bytes, but that's old information. There's a length component in the (Dec 2011) framing. And btw, there a flag in the framing spec that specifies whether the frame is the whole "message" or a "message fragment", ie, there are other frames that make up this "message". Its up to the receiver to combine the fragments correctly to pass up to the application code. Normally you don't have to think about this unless you have very large "messages" (think of WS "messages" as "data" rather than true messages... WS is not really a "messaging" protocol per se).

But note, WebSocket is a low-level transport. Think of it like a web-based TCP. Application programmers should use high-level protocols "over WS/WSS" and not worry about ordering, reconnection, presence, pub/sub, tuple-spaces, guaranteed delivery, etc, etc. If we don't do this, dozens and dozens of decades-old application protocols will be re-invented.

FrankG
  • 515
  • 2
  • 3
  • 1
    could a message frame be entirely broken? i.e. instead of hello be hel#@ ? – MrNobody Jun 08 '20 at 09:01
  • so if each message is a complete JSON encoded piece of data, I can always safely `JSON.parse` on each message on the other end and never have a problem? – Michael Feb 09 '21 at 04:33
1

Having a very bad connection you may lose a message (however it should be resend with tcp), but it's very unlikely to be splitted in such a way. Each text message has boundaries - start (0x00) and finish (0xFF) bytes. Browser should not mess messages. Likely you can get messages in another order.

How can you be more sure:

  1. Add your own control sums to messages (but indeed it's overhead).
  2. Use wss (websockets+tls/ssl) protocol - corrupted messages would not be decrypted well.
Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59