quantumpotato
quantumpotato

Reputation: 9767

Get a reference to Websocket connection in Cowboy

I am following this example. I've modified my ws_handler slightly with "websocket_handle({text, <<"h">>}, State) -> {reply, {text, << "You h-in!">>}, State};"

to confirm I could detect specific messages.

I want to track websocket connections. In https://ninenines.eu/docs/en/cowboy/1.0/guide/ws_handlers/ I see there's a Req object but I'm not sure what to search for to see what it contains.

I found this communicating between http handler and websocket handler in Cowboy ; I don't understand the meaning of the example answer though.

https://github.com/ninenines/cowboy/tree/master/examples/websocket is using pkg_cowboy_commit = 1.0.4 in the erlang.mk, I haven't found an example using the latest 2.0 cowboy.

I want to track websocket connections via an ID or PID in a list, remove a reference when they disconnect, etc. I see no way of doing this besides sending the first bytes of a text on each message being the ID and this seems wrong.

In contrast socket.io, for example, you get socket.id - I want the same kind of reference in Erlang.

Upvotes: 1

Views: 320

Answers (1)

quantumpotato
quantumpotato

Reputation: 9767

I am thinking something like creating a process that references the websocket State. So on

websocket_init(State) ->

Pass the State to a process, and add that new process PID to the State of the websocket

then in

websocket_handle({text, Msg}, State) ->

a custom {reply, Reply} can be sent by loading data from the PID which is connected to custom domain logic.

Upvotes: 0

Related Questions