Websockets: How do I get the channelID when using {channel}

I’m trying to get the channelID from inside a websocket listener component when using the special {channel} place holder in the endpoint. The websocket docs indicate that clients are automatically subscribed to the channel specified where {channel} exists in the endpoint, which I assume is the channelID that would be used in the ConnectionManager.broadcast() method.

See docs about endpoints and place holders: https://github.com/isapir/lucee-websocket/wiki/WebsocketRegister-Function

So for example, defining the endpoint: /ws/chat/{channel} and then connecting to /ws/chat/foobar, my understanding is that the client is automatically connected to the foobar channel ID.

My question is, how do I get the channel ID [foobar] from inside the onSend() method of my listener (or from any of the methods in the listener) in order to pass it to the ConnectionManager.broadcast() method? Consider this simplified example:

1. The browser connects to the ‘/ws/chat/foobar’ channel and sends a message to everyone:

<script>
var websocket = new WebSocket('/ws/chat/foobar');
websocket.send('Sending to all foobar people!');
</script>

2. Here’s the listener for the /ws/chat/{channel} endpoint - how do I broadcast that message to the foobar channel?

component {

    function onMessage(websocket, message, sessionScope, applicationScope) {

        var connMgr = arguments.websocket.getConnectionManager();
        var channelID = ??; // HOW DO I GET THE CHANNEL ID?? Should be "foobar"
        
        // broadcast the message to all subscribers of the channel
        connMgr.broadcast("foobar", message);
    }

}

And my follow up question is how would you access other non-special placeholders from inside the listener? For example:

/ws/users/{userid}/{param1}/{param2}

I figured it out. According to the docs for the WebSocket API, I can call WebSockets.getPathParameters(). So my listener.onMessage() method would look like this:

component {

    function onMessage(websocket, message, sessionScope, applicationScope) {
        
        var response = {
            broadcasted: false
        };

        var pathParams = Arguments.websocket.getPathParameters();
        var channelID = StructKeyExists(pathParams, "channel") ? pathParams.channel : "";
        
        if (channelID != "") {
            var connMgr = arguments.websocket.getConnectionManager();
            // broadcast the message to all subscribers of the channel
            connMgr.broadcast(channelID, message);
            response.broadcasted = true;
        }

        return(SerializeJSON(response));

    } // onMessage()

}

Here’s the WebSocket API doc that explains the getPathParameters() method:

1 Like

I’m glad you found the solution in the docs.

I spent a lot of time documenting this so please (and that’s a message for everyone) read the docs first.

Igal