(there is no way of sending these from JavaScript, and clients don't initiate them--it really appears to be the server's responsibility).
Below is a general-purpose function for sending a message to a websocket client. I'm now working on enumerating the connections and looking for a simple way of guaranteeing that they are locked correctly so that send calls don't get interlaced.
/**
Send a message to a client.
This should not be invoked on a connection while any other mg_write/mg_printf operation
is occuring on that connection. Mongoose does not provide a per-connection mutex,
so it is necessary for the application to either hold a global lock on mg_write, or
to hold a table mapping connections to locks.
Note that POSIX/Winsock's send() is threadsafe
but mongoose's mg_printf/mg_write is not (because of the loop in push(), although that is only
a problem if the packet is large or outgoing buffer is full).
*/
void websocket_write(struct mg_connection* conn, int opcode, const char* data, size_t dataLen) {
unsigned char* copy = (unsigned char*)malloc(dataLen + 4);
size_t copyLen = 0;
copy[0] = 0x80 + (opcode & 0xF);
if (dataLen < 126) {
copy[1] = dataLen;
System::memcpy(copy + 2, data, dataLen);
copyLen = 2 + dataLen;
} else if (dataLen < 0xFFFF) {
copy[1] = 126;
*(uint16*)(data + 2) = htons(dataLen);
System::memcpy(copy + 4, data, dataLen);
copyLen = 4 + dataLen;
} else {
alwaysAssertM(false, "Packets of length larger than 16 bits are not supported in this implementation.");
}
mg_write(conn, copy, copyLen);
free(copy);
}