[Libwebsockets] message fragmentation

Andy Green andy at warmcat.com
Sat Jan 19 00:26:04 CET 2019



On 19/01/2019 02:28, Alexander Zvyagin wrote:
> Hi,
> 
> I started to use libwebsockets last week, so I am sorry in advance if
> my question is naive or I miss something in the documentation.
> 
> I am sending a message from my protocol, the message length is 3780
> bytes. The buffer size is 8192 bytes, lws_write() reports that the
> message has been sent. But on the client side in javascript code I
> receive only first 2213 bytes of the message.
> 
> How do I detect (in javascript) that the message was fragmented? How
> do I get the rest of the message?

Javascript takes the approach to only use logically complete messages... 
if they are fragmented, either by tcp fragmentation or logical ws 
fragmentation, then JS itself waits and assembles the complete message 
before creating the JS event informing the user code that a ws message 
arrived.

So the real problem is slightly different, right now you are actually 
sending a complete (not fragmented) ws message of length 2213, otherwise 
such a ws message could not have appeared in your JS.

By default, each time you use lws_write(), it creates a logically 
complete message.  You have to give it appropriate flags to indicate 
that there are multiple fragments in your message.

Since the RFC6455 rules and the flags on top are a bit nonobvious, 
there's a helper api to figure out the flags.

/**
  * lws_write_ws_flags() - Helper for multi-frame ws message flags
  *
  * \param initial: the lws_write flag to use for the start fragment, eg,
  *		   LWS_WRITE_TEXT
  * \param is_start: nonzero if this is the first fragment of the message
  * \param is_end: nonzero if this is the last fragment of the message
  *
  * Returns the correct LWS_WRITE_ flag to use for each fragment of a 
message
  * in turn.
  */
static LWS_INLINE int
lws_write_ws_flags(int initial, int is_start, int is_end)
...

https://libwebsockets.org/git/libwebsockets/tree/include/libwebsockets/lws-write.h#n220-246

You can see it being used here:

https://libwebsockets.org/git/libwebsockets/tree/minimal-examples/ws-server/minimal-ws-server-pmd-bulk/protocol_lws_minimal_pmd_bulk.c#n133

-Andy

> Thanks a lot in advance!
> Alexander.
> _______________________________________________
> Libwebsockets mailing list
> Libwebsockets at ml.libwebsockets.org
> https://libwebsockets.org/mailman/listinfo/libwebsockets
> 


More information about the Libwebsockets mailing list