libwebsockets icon indicating copy to clipboard operation
libwebsockets copied to clipboard

Send a large message by using ws

Open youroxygen opened this issue 4 months ago • 3 comments

I want to send a large message more than 1M as a client by using ws, I don't found a demo to reference, Only LWS_WRITE_NO_FIN I found may be useful,but when LWS_CALLBACK_CLIENT_WRITEABLE is active, it only could write a certain amount of data,is there has some demo to handle this scenario

youroxygen avatar Aug 25 '25 10:08 youroxygen

There's a public helper lws_write_ws_flags() which simplifies doing this, it returns the flags to pass on to lws_write(). The first arg is the type of the message, LWS_WRITE_BINARY or LWS_WRITE_TEXT. The second arg is nonzero (true) if this is the first fragment in the message. The third arg is nonzero (true) if this is the last fragment in the message.

You send "a chunk" of your message, say, 4096 bytes, using lws_write_ws_flags() to set the lws_write() flags. If it wasn't the last fragment, ask for lws_callback_on_writable(wsi); and return from the callback.

This will keep going for as long as it needs to send the whole huge message, and take care of the FIN flags etc automatically.

lws-team avatar Aug 25 '25 13:08 lws-team

Are you saying that I need to first split my message into 4K sized chunks, and then use the lws_write_ws_flags() function to mark the first and last chunk? Every time the LWS_CALLBACK_CLIENT_WRITEABLE callback is triggered, one of the chunks will be sent until the last chunk is sent out

youroxygen avatar Aug 25 '25 14:08 youroxygen

I dunno what "split my message into 4K sized chunks" means to you, but if the linear 1MB message is in memory somewhere, you can move a pointer over it in 4K hops. There isn't any "splitting" needed other than just focus on each 4K in turn.

lws-team avatar Aug 25 '25 14:08 lws-team