【问题标题】:communicating between http handler and websocket handler in CowboyCowboy 中的 http 处理程序和 websocket 处理程序之间的通信
【发布时间】:2015-02-27 01:18:27
【问题描述】:

我想在 Cowboy 中创建一个从另一个 Cowboy 处理程序获取其数据的 websocket 应用程序。假设我想结合牛仔的 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 在它们之间传递消息?我将不胜感激示例代码的答案,该示例代码显示了处理程序的胶水代码 - 我真的不知道从哪里开始将两个处理程序连接在一起。

【问题讨论】:

    标签: websocket erlang cowboy


    【解决方案1】:

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

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

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

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

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

    您可以使用gproc_ps:subscribe/2gproc pubsub 注册进程,并使用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);
    

    【讨论】:

    • 刚刚测试,它的工作原理!非常感谢!与 erlang 中可用的其他方法相比,您知道这种方法是否有任何显着的性能或可伸缩性缺陷(例如,如果 pub 和 sub 在不同的机器上等)?将我自己的 gen_server for oub/sub 放在 echo 和 websocket 处理程序之间会比 gproc 更高效/可扩展吗?我试图了解我是否可以坚持使用 gproc 来做一个宠物项目以外的事情(在 pub/sub 线上进行大量通信(高 pub/sub 速率和节点数量)。
    猜你喜欢
    • 2011-10-29
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 2021-09-08
    • 2011-03-04
    • 1970-01-01
    相关资源
    最近更新 更多