4

我想在 Cowboy 中创建一个 websocket 应用程序,从另一个 Cowboy 处理程序获取其数据。假设我想结合牛仔的 Echo_get 示例:https ://github.com/ninenines/cowboy/tree/master/examples/echo_get/src

以 websocket 为例

https://github.com/ninenines/cowboy/tree/master/examples/websocket/src

以这种方式,对 Echo 的 GET 请求应通过 websocket 处理程序向该示例中的 html 页面发送“推送”。

最简单的方法是什么?我可以以某种简单的方式使用“管道”运算符吗?我是否需要创建和中间 gen_something 在它们之间传递消息?我将不胜感激示例代码的答案,该示例代码显示了处理程序的胶水代码 - 我真的不知道从哪里开始将两个处理程序连接在一起。

4

1 回答 1

7

牛仔中的 websocket 处理程序是一个长期存在的请求进程,您可以向其发送 websocket 或 erlang 消息。

在您的情况下,有两种类型的流程:

  • websocket 进程:带有向客户端打开的 websocket 连接的 websocket 处理程序。
  • echo 进程:当客户端使用参数访问 echo 处理程序时的进程。

这个想法是,echo 进程向 websocket 进程发送一条 erlang 消息,而 websocket 进程又将向客户端发送一条消息。

为了让您的 echo 进程可以向您的 websocket 进程发送消息,您需要保留一个要向其发送消息的 websocket 进程的列表。Gproc是一个非常有用的库。

您可以使用 向gproc pubsub注册进程gproc_ps:subscribe/2,并使用 向注册的进程发送消息gproc_ps:publish/3

Cowboy websocket 进程使用websocket_info/3函数接收 erlang 消息。

例如,websocket 处理程序可能是这样的:

websocket_init(_, Req, _Opts) ->
  ...
  % l is for local process registration
  % echo is the name of the event you register the process to
  gproc_ps:subscribe(l, echo),
  ...

websocket_info({gproc_ps_event, echo, Echo}, Req, State) ->
  % sending the Echo to the client
  {reply, {text, Echo}, Req, State};

和这样的回声处理程序:

echo(<<"GET">>, Echo, Req) ->
    % sending the echo message to the websockets handlers
    gproc_ps:publish(l, echo, Echo),
    cowboy_req:reply(200, [
        {<<"content-type">>, <<"text/plain; charset=utf-8">>}
    ], Echo, Req);
于 2014-12-31T07:38:10.727 回答