RejectedSoftware Forums

Sign up

Broadcasting to all Websockets

I'm trying to implement a simple server that broadcasts messages received from a websocket to all other websockets. For this I'm keeping track of all open websockets in a global variable:

WebSocket[uint] sockets;
uint            id = 0;
void handleConn(WebSocket ws) {
    sockets[id++] = ws;
    ...
}
static this() {
    auto router = new URLRouter;
    router.get("/ws", handleWebSockets(&handleConn));
}

This version of handleWebSockets providing a WebSocket is deprecated. Instead, I should use a scope parameter:

void handleConn(scope WebSocket ws) { ... }

Currently dmd accepts this change, even though it would leak a reference to a scope parameter.

How can I implement broadcasting with scope WebSocket?

Re: Broadcasting to all Websockets

On 2014-09-12 20:33:16 +0000, Alexander Breckel said:

I'm trying to implement a simple server that broadcasts messages
received from a websocket to all other websockets. For this I'm keeping
track of all open websockets in a global variable:


WebSocket[uint] sockets;

uint            id = 0;

void handleConn(WebSocket ws) {

    sockets[id++] = ws;

    ...

}

static this() {

    auto router = new URLRouter;

    router.get("/ws", handleWebSockets(&handleConn));

}

This version of handleWebSockets providing a WebSocket is deprecated.
Instead, I should use a scope parameter:


void handleConn(scope WebSocket ws) { ... }

Currently dmd accepts this change, even though it would leak a
reference to a scope parameter.

How can I implement broadcasting with scope WebSocket?

Add some scope guards to remove the websocket from the global list when
it closes.