erlang - how can I send a param into websock connection using cowboy -
in cowboy websocket example in toppage_handler.erl
handle(req, state) -> {echo, req2} = cowboy_req:qs_val(<<"echo">>, req), {ok, req, state}.
i want param echo following function
for example:
localhost:8080/?echo=123
in ws_handler.erl
websocket_init(_transportname, req, _opts) -> %%how can use echo(123) here? erlang:start_timer(1000, self(), <<"hello!">>), {ok, req, undefined_state}.
a simple workaround use path bindings :
in routes :
dispatch = cowboy_router:compile([ %% {hostmatch, list({pathmatch, handler, opts})} {'_', [{"/echo/:echo", my_handler, []}]} ]),
then in code :
{echo, req2} = cowboy_req(echo,req)
it's best in websocket_handle because able send response socket. in init, have carry in state, :
websocket_init(_transportname, req, _opts) -> {echo, req2} = cowboy_req:binding(echo,req), erlang:start_timer(1000, self(), <<"hello!">>), {ok, req2, {echo}}. websocket_handle(_frame, req, {echo}) -> {reply, {text, echo}, req, state}.
as websocket designed handle long term connections, use bindings support information channels, user ids, etc. not data in "echo" because want send multiple different texts echo without closing , reopen websocket connection each time change url.
Comments
Post a Comment