我想在牛仔中创建一个websocket应用程序,它从另一个牛仔处理程序那里获取数据。假设我想结合牛仔的Echo_get示例:获得/重新分配
使用websocket示例
https://github.com/ninenines/cowboy/tree/master/examples/websocket/src
在这种情况下,GET对Echo的请求应该通过websocket处理程序向该示例中的html页面发送一个"push“。
最简单的方法是什么?我能用一些简单的方式使用“管道”操作员吗?我是否需要创建和中间gen_something来在它们之间传递消息?我希望得到一个示例代码的答案,它显示了处理程序的胶水代码--我真的不知道从哪里开始将这两个处理程序连接起来。
发布于 2014-12-31 07:38:10
牛仔中的websocket处理程序是一个长期存在的请求进程,您可以向其发送websocket或erlang消息。
在您的例子中,有两种类型的流程:
其思想是,回显进程向websocket进程发送erlang消息,然后将消息发送给客户端。
由于回送处理可以向websocket进程发送消息,因此需要保留要向其发送消息的websocket进程的列表。为此目的,Gproc是一个非常有用的库。
您可以使用gproc青春期向gproc_ps:subscribe/2注册进程,并使用gproc_ps:publish/3向已注册的进程发送消息。
牛仔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);https://stackoverflow.com/questions/27712843
复制相似问题