websocket - Cowboy 中的 http 处理程序和 websocket 处理程序之间的通信

标签 websocket erlang cowboy

我想在 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 来在它们之间传递消息?我很感激示例代码的答案,其中显示了处理程序的胶水代码 - 我真的不知道从哪里开始将两个处理程序连接在一起。

最佳答案

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

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

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

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

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

    您可以将进程注册到 gproc pubsubgproc_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);
    

    关于websocket - Cowboy 中的 http 处理程序和 websocket 处理程序之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712843/

    相关文章:

    erlang - 如何在不关闭 erlang VM 的情况下离开 erlang shell

    websocket - erlang 中带有牛仔和 websocket 的聊天室

    linux - 在 Yaws 和 Cowboy 上自动从端口 80 重定向到端口 433

    javascript - WebSocket 关闭并出现协议(protocol)错误 1002

    java - 使用 Netty 将 websockets 与在 tomcat 中运行的 Spring Web 应用程序集成

    logging - 如何查看使用 Edeliver 部署的 Phoenix Web 应用程序中的生产日志?

    emacs - 如何从 Erlang 脚本调用 Emacs?

    javascript - Socket.IO 将数据发送到我自己的房间

    performance - 使用 websockets 构建整个网站?重访

    rest - 为 Cowboy REST API 启用 CORS