[Libwebsockets] Modifying libwebsocket.user_space

Andy Green andy at warmcat.com
Tue Aug 19 02:28:48 CEST 2014

On 19 August 2014 00:58:24 GMT+08:00, Roger Light <roger at atchoo.org> wrote:
>I'm in the situation where events outside of lws may require me to
>update the contents of the user_space member of a single struct
>libwebsocket. Any suggestions on how to proceed?
>I have a struct that represents a client in my application. It keeps a
>pointer to the wsi struct.
>The easiest solution from my point of view would be the creation of a
>libwebsocket_get_user() function. I see that this has been discussed
>before (e.g.
>) and dismissed. I understand the reasoning there, but at least in my
>case if service had cleaned up and freed the wsi, then my client
>struct would also have been freed and I wouldn't be in this situation.
>This is all single threaded, right? :)

After a rough start trying to work with people with multithreaded apps, it's boiled down that it should be safe to call the on_writeable() callback for a wsi externally, from an external wsi list that is maintained by following the ESTABLISHED and CLOSED callbacks.

So generally, on_writeable() is threadsafe and that's enough to move all the other processing back into the service thread context ON_WRITEABLE callback; from there you can write websockets data or do whatever else you need.

>My suggested solution is below, but I'd be happy to hear other ideas.

Some people have a huge number of clients connected, so this is an expensive call for them.  If all connected clients do it just aimed at themselves you end up with the square of (number of clients - 1) wasted callbacks; number of clients can be > 10000.

>If there was a version of libwebsocket_callback_all_protocol()
>available that let me pass in something that would end up in the
>"user" and/or "in" arguments of my callback then I think it would
>remove any risk of a bad wsi access and I wouldn't grumble *too* much
>about having to iterate over all of the clients just to find the one I
>was interested in. It would certainly be a huge improvement over the
>horrific hack that I'm using at the moment.

If you follow the ESTABLISHED and CLOSED callbacks to enforce your other wsi list's lifetime (with locking if multithreaded), and the only thing you use it for is asking for a writeable callback, then you shouldn't get any bad wsi access.

Then you can just use a member in your *user struct to deliver the pointer or whatever it is you want processed.

Is that enough?


>Libwebsockets mailing list
>Libwebsockets at ml.libwebsockets.org

More information about the Libwebsockets mailing list