I'm trying to create a chatroom with cowboy websocket handler.
I want that messages those come from every will be forwarded to other sockets as well, just like a chat group.
I don't have any idea how to implement this?
And I don't know how to save sockets that are connected to websocket so we can send messages to them.
I have this cowboy handler:
-module(chat_conn).
-export([ init/2
, websocket_init/1
, websocket_handle/2
, websocket_info/2
, terminate/3
]).
-include("chat.hrl").
init(Req, [WsConnIdleTimeout]) ->
?LOG_DEBUG("[CHAT-CONN] New HTTP Request on: /api , Pid: ~p", [self()]),
WsOpts = #{idle_timeout => WsConnIdleTimeout},
State = #{counter => 0},
{cowboy_websocket, Req, State, WsOpts}.
websocket_init(State0) ->
?LOG_DEBUG("[FOOZI-CONN] HTTP Upgraded to WebSocketm pid: ~p", [self()]),
NewState = State0,
{ok, NewState}.
websocket_handle({text, PlainRequest}, #{counter := Counter0} = State) ->
?LOG_DEBUG("[HIGGS-CONN] Receive New Message: ~p, Pid: ~p" , [PlainRequest, self()]),
NewCounter = Counter0 + 1,
Reply = list_to_binary("Counter is: " ++ integer_to_list(NewCounter)),
NewState = #{counter => NewCounter},
{reply, {text, Reply}, NewState};
%{ok, State};
websocket_handle(Frame, State) ->
?LOG_INFO("[HIGGS-CONN] Invalid Frame => ~p", [Frame]),
{stop, State}.
websocket_info(Message, State) ->
?LOG_INFO("[CONN-INFO] Unhandled message! => Message: ~p", [Message]),
{reply, {text, list_to_binary(Message)}, State}.
%{ok, State}.
terminate(Reason, _, State) ->
?LOG_INFO("[CONN-TERMINATE] Terminated! => Pid: ~p, Reason: ~p, State: ~p", [self(), Reason, State]),
ok.
question from:
https://stackoverflow.com/questions/66059636/chat-room-in-erlang-with-cowboy-and-websocket