我正在使用 yaws(Erlang 框架)进行套接字通信。我可以使用 websocket_send 从服务器向用户发送消息,但是我需要指定用户的 PID,这意味着我可以将消息发送回该用户。但是,我想向所有连接的用户发送消息。有什么办法吗?
最佳答案
每次建立 websocket 连接时,都会为该连接创建一个新的 gen_server 进程。因此,这些服务器中的每一个都对应一个 websocket 连接。因此 websocket_send 需要 gen_server 的 PID。
为了向所有连接的客户端发送消息,您需要维护所有 gen_servers 的 PID。这可以通过拥有自己的 gen_server 或使用 ets 来完成。
类似于 sending the Pid to gen_server
您可以在 websocket 回调 init 函数中发送 Pid
init(Args) ->
gen_server:cast(?YOURSERVER,{connection_open, self()}),
{ok, []}.
终止期间
terminate(Reason, State) ->
gen_server:cast(?YOURSERVER,{connection_close, self()}).
您的 gen_server handle_cast 可能如下所示
handle_cast({connection_open, Pid}, Pids) ->
{noreply, [Pid | Pids]};
handle_cast({connection_close, Pid}, Pids) ->
{noreply, lists:delete(Pid, Pids)};
handle_cast({send_to_all, Msg}, Pids) ->
[yaws_api:websocket_send(Pid, Msg) || Pid <- Pids, is_process_alive(Pid)],
{noreply, Pids}.
关于erlang - Yaws websocket 向所有连接的用户发送消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15700389/