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

Erlang Yaws websocket向所有连接的用户发送消息,erlang,websocket,yaws,Erlang,Websocket,Yaws,我正在使用yaws(erlangframework)进行套接字通信。我可以使用websocket\u send将消息从服务器发送回用户,但是我需要指定用户的PID,这意味着我可以将消息发送回该用户。但是,我想向所有连接的用户发送消息。有什么方法可以做到这一点吗?这需要一种涉及内存存储的综合方法。例如,每个用户可能都有一个进程保存套接字连接,因此,您可以在mnesia或ets tablee.t.c.中保存一个记录,例如:#connected_user{pid=pid,username=userna

我正在使用yaws(erlangframework)进行套接字通信。我可以使用websocket\u send将消息从服务器发送回用户,但是我需要指定用户的PID,这意味着我可以将消息发送回该用户。但是,我想向所有连接的用户发送消息。有什么方法可以做到这一点吗?

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


稍后在了解到这个问题后,您将转到会话管理,如何处理脱机消息,最重要的是
presence
。不管怎样,当一条消息传入时,有了目标用户名,那么您将从我们的表中进行查找,并获得相应的
Pid
,然后将此消息发送给它,然后,它将通过它的live Web套接字发送它。

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

要向所有连接的客户端发送消息,您需要维护所有gen_服务器的PID。这可以通过拥有自己的gen_服务器或使用ets来实现

近似 您可以在websocket回调init函数中发送Pid

init(Args) ->
  gen_server:cast(?YOURSERVER,{connection_open, self()}),
  {ok, []}.
终止期间

terminate(Reason, State) ->
  gen_server:cast(?YOURSERVER,{connection_close, self()}).
您的gen_服务器句柄类型可能如下所示

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}.
handle\u cast({connection\u open,Pid},Pid)->
{noreply,[Pid|Pid]};
handle_cast({connection_close,Pid},Pid)->
{noreply,list:delete(Pid,Pid)};
handle_cast({send_to_all,Msg},Pids)->

[yaws_api:websocket_send(Pid,Msg)| | Pid成功了!!!使用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

Hmmm..使用消息队列实现此目的如何?因此,所有用户都使用一个队列连接,当一个用户发布消息时,消息通过yaws进入erlang模块,然后发布到rabbitMQ,rabbitMQ将消息发布给所有用户???感谢vinod的回复..如何使用消息队列实现此目的。因此,所有用户使用一个队列连接,当消息从一个用户发布时,它通过yaws进入erlang模块,然后发布到rabbitMQ,rabbitMQ将消息发布给所有用户???如果您使用消息队列,则通过它进行路由是一个好主意。但如果您仅考虑为此目的使用它,则可能会产生开销。每个yaws创建的gen_服务器应该注册到该频道。然后它可以在handle_info中接收消息,您可以在其中执行yaws_api:websocket_send(self(),Msg)Hi-Vinod..我对erlang非常陌生,所以您有使用ETS的示例代码吗