valenok/mongoose — pull request #139 by morgan3d (2013-03-26 02:21:51+00:00)
Title: Synchronized websocket communication

Unlike normal HTTP requests, a websocket is a full duplex, persistent
connection. The server or client may initiate a message at any time to
one another. This creates a need for two new features:

* A per-connection mutex to allow the application to ensure that it is
not trying to invoke mg_write on multiple threads simultaneously (e.g.,
when responding to a client message and when initiating its own) or when
the connection is in the process of being closed by the server.

* A callback to notify the application when a websocket closes (so that
it can drop the client from its list of connected clients). The
preexisting client-closed handling in the error handler does not catch
all cases where a client drops. This is the more essential part of the
patch--the mutex can be worked around with some awkwardness, but this
cannot because the mg_connection objects are reused over multiple
connections.

I created this hopefully-minimal patch to add these two features. I
also include a helper function for handling dynamically-sized writes,
which have some tedious boilerplate under the websocket protocol.