在Cowboy中的http处理程序和websocket处理程序之间进行通信

vol*_*ire 4 erlang websocket 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以在它们之间传递消息?我希望得到一个示例代码的答案,显示处理程序的粘合代码 - 我真的不知道从哪里开始将两个处理程序连接在一起.

Eri*_*ric 7

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

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

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

我们的想法是,echo进程向websocket进程发送一条erlang消息,然后该消息将向客户端发送消息.

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

你可以注册流程GPROC发布订阅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};
Run Code Online (Sandbox Code Playgroud)

像这样的echo处理程序:

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);
Run Code Online (Sandbox Code Playgroud)