1
votes

I've been looking into Cowboy websockets in Erlang.

My goal is to send a websocket frame to an existing websocket connection. I found docs under Receiving Erlang messages stating that I can send an "Erlang message" and it will be handled by websocket_info/2.

What does this documentation mean by "Sending an Erlang message"?

I've tried something like:

init(Req, State) ->
  Self = self(),
  spawn(fun() ->
    timer:sleep(2000),
    Self ! "Hoii"
  end),
  {cowboy_websocket, Req, State}.

websocket_info(_Info, State) ->
  io:fwrite("Info received\n"),
  {ok, State}.

But this seems to do nothing.

How can I send an Erlang message for my websocket_info/2 to handle for an existing websocket connection?

1

1 Answers

2
votes

After just a few minutes, I figured out that I was simply sending the self() ! "Msg" too early.

Cowboy websockets also have a function websocket_init/1 and by moving my code into that function I was able to recieve the websocket_info/2 message.

websocket_init(State) ->
  Self = self(),
  spawn(fun() ->
    timer:sleep(2000),
    Self ! "Hoii"
  end),
  {ok, State}.

websocket_info(_Info, State) ->
  io:fwrite("Info received\n"),
  {ok, State}.

Note the message is being sent now from the websocket_init/1 function rather than just init/2.