0

in cowboy websocket example in toppage_handler.erl

    handle(Req, State) ->
      {Echo, Req2} = cowboy_req:qs_val(<<"echo">>, Req),
      {ok, Req, State}.

I want to get the param Echo into the following function

for example:

localhost:8080/?echo=123

in ws_handler.erl

    websocket_init(_TransportName, Req, _Opts) ->
         %%How can I use the Echo(123) here?
         erlang:start_timer(1000, self(), <<"Hello!">>),
         {ok, Req, undefined_state}.
ter
  • 289
  • 1
  • 3
  • 6

1 Answers1

0

A simple workaround is to use path bindings :

In your routes :

Dispatch = cowboy_router:compile([
    %% {HostMatch, list({PathMatch, Handler, Opts})}
    {'_', [{"/echo/:echo", my_handler, []}]}
]),

Then in your code :

{Echo, Req2} = cowboy_req(echo,Req)

It's best to do this in Websocket_handle because you will be able to send your response to the socket. In init, you will have to carry it in your state, like this :

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 is designed to handle long term connections, i use bindings like this to support information like channels, user ids, etc. But not data like in "echo" because you will want to send multiple different texts to echo without closing and reopen a websocket connection each time just to change URL.

lud
  • 1,941
  • 20
  • 35
  • do not have the param echo,either – ter Aug 09 '13 at 02:46
  • All i want to do is send a param into websocket in erlang, but how? – ter Aug 09 '13 at 02:46
  • ok so i edited my answer with a technique that i actually use, so it works. If it doesn't, you will have to show more code of yours. cheers – lud Aug 09 '13 at 08:03