Yaws websocket向所有连接的用户发送消息

时间:2013-03-29 09:13:53

标签: erlang websocket yaws

我正在使用yaws(Erlang框架)进行套接字通信。我可以使用 websocket_send 从服务器向用户发送消息,但是我需要指定用户的PID,这意味着我可以将消息发送回该用户。但是,我想向所有连接的用户发送消息。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:2)

每次建立websocket连接时,都会为该连接创建一个新的gen_server进程。因此,这些服务器中的每一个对应于一个websocket连接。因此,websocket_send需要gen_server的PID。

要向所有连接的客户端发送消息,您需要维护所有gen_servers的PID。这可以通过拥有自己的gen_server或使用ets来完成。

sending the Pid to gen_server 相似 你可以在websocket回调初始化函数中发送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}.

答案 1 :(得分:1)

搞定了!!!使用GProc:)

Gproc是Erlang的一个进程字典,它提供了许多超出内置字典的有用功能:

Use any term as a process alias

Register a process under several aliases

Non-unique properties can be registered simultaneously by many processes

QLC and match specification interface for efficient queries on the dictionary

Await registration, let's you wait until a process registers itself

Atomically give away registered names and properties to another process

Counters, and aggregated counters, which automatically maintain the total of all counters with a given name

Global registry, with all the above functions applied to a network of nodes

答案 2 :(得分:0)

这需要一种涉及内存存储的综合方法。例如,每个用户可能有一个持有套接字连接的进程,因此,您可以在mnesiaets table e.t.c中保存。记录如:#connected_user{pid = Pid,username = Username,other_params = []}

在稍后提升您对此问题的看法之后,您将进入会话管理,如何处理离线消息,最重要的是presence。无论如何,当有消息进来时,有目的地用户名,那么你将从我们的表中查找并得到相应的Pid,然后发送这条消息,然后它将通过它发送它live Web Socket。

相关问题