Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is websocket a stream-based or package-based protocol?

Imagine that I have server and client talking via WebSocket. Each of time sends another chunks of data. Different chunks may have different length.

Am I guaranteed, that if server sends chunk in one call, then client will receive it in one message callback and vice-versa? I.e., does WebSocket have embedded 'packing' ability, so I don't have to care if my data is splitted among several callbacks during transmission or it doesn't?

like image 905
yeputons Avatar asked Jan 09 '14 15:01

yeputons


2 Answers

Theoretically the WebSocket protocol presents a message based protocol. However, bear in mind that...

  • WebSocket messages consist of one or more frames.
  • A frame can be either a complete frame or a fragmented frame.
  • Messages themselves do not have any length indication built into the protocol, only frames do.
  • Frames can have a payload length of up to 9,223,372,036,854,775,807 bytes (due to the fact that the protocol allows for a 63bit length indicator).
  • The primary purpose of fragmentation is to allow sending a message that is of unknown size when the message is started without having to buffer that message.

So...

A single WebSocket "message" could consist of an unlimited number of 9,223,372,036,854,775,807 byte fragments.

This may make it difficult for an implementation to always deliver complete messages to you via its API...

So whilst, in the general case, the answer to your question is that the WebSocket protocol is a message based protocol and you don't have to manually frame your messages. The API that you're using to use the protocol may either have message size limits in place (to allow it to guarantee delivery of messages as a single chunk) or may present a streaming interface to allow for unlimited sized messages.

I ranted about this back during the standardisation process here.

like image 171
Len Holgate Avatar answered Oct 21 '22 12:10

Len Holgate


WebSocket is a message-based protocol, so if you send a chunk of data as the payload of a WebSocket message, the peer will receive one separate WebSocket message with exactly that chunk of data as payload.

like image 28
oberstet Avatar answered Oct 21 '22 13:10

oberstet