Reputation: 820
Now that Im using cowboy to serve as a websocket server, I understand that the handler implements a behavior called cowboy_websocket_handler
and that the websocket_handle/3
function is called every time we receive a request and that to reply back to the request, we reply using {reply, X, _}
. However since WebSocket is a bi-directional protocol and that server can reach to a client without a request, how do I send some data to the client, not in the web_socket_handle
.
I am expecting something in the handler along the lines of
send(Client, Data)
. Am I thinking in the right direction? ? Thanks!
If yes, does cowboy provide some API to do so?
Upvotes: 0
Views: 462
Reputation: 11588
To quote the docs:
Cowboy will call websocket_info/2 whenever an Erlang message arrives.
The handler can handle or ignore the messages. It can also send frames to the client or stop the connection.
The following snippet forwards log messages to the client and ignores all others:
websocket_info({log, Text}, State) ->
{reply, {text, Text}, State};
websocket_info(_Info, State) ->
{ok, State}.
So all you have to do is send a message to your handler from another process (or from itself if you wish), and implement websocket_info as above to send a frame to the client.
Upvotes: 1