我想在 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 消息。
在您的情况下,有两种类型的过程:
这个想法是,echo 进程向 websocket 进程发送一条 erlang 消息,后者又将向客户端发送一条消息。
由于您的 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);
关于websocket - Cowboy 中的 http 处理程序和 websocket 处理程序之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712843/