0
Fork 0
mirror of https://github.com/ninenines/cowboy.git synced 2025-07-14 12:20:24 +00:00

Fix timer-sent events in the websocket example

This commit is contained in:
Loïc Hoguin 2016-08-11 11:06:03 +02:00
parent 5fa5ba8ca4
commit e2d5c268aa
3 changed files with 29 additions and 4 deletions

View file

@ -1,13 +1,17 @@
-module(ws_handler). -module(ws_handler).
-export([init/2]). -export([init/2]).
-export([websocket_init/2]).
-export([websocket_handle/3]). -export([websocket_handle/3]).
-export([websocket_info/3]). -export([websocket_info/3]).
init(Req, Opts) -> init(Req, Opts) ->
erlang:start_timer(1000, self(), <<"Hello!">>),
{cowboy_websocket, Req, Opts}. {cowboy_websocket, Req, Opts}.
websocket_init(Req, State) ->
erlang:start_timer(1000, self(), <<"Hello!">>),
{ok, Req, State}.
websocket_handle({text, Msg}, Req, State) -> websocket_handle({text, Msg}, Req, State) ->
{reply, {text, << "That's what she said! ", Msg/binary >>}, Req, State}; {reply, {text, << "That's what she said! ", Msg/binary >>}, Req, State};
websocket_handle(_Data, Req, State) -> websocket_handle(_Data, Req, State) ->

View file

@ -32,6 +32,12 @@
| {module(), Req, any(), timeout()} | {module(), Req, any(), timeout()}
| {module(), Req, any(), timeout(), hibernate} | {module(), Req, any(), timeout(), hibernate}
when Req::cowboy_req:req(). when Req::cowboy_req:req().
-callback websocket_init(Req, State)
-> {ok, Req, State}
when Req::cowboy_req:req(), State::any().
-optional_callbacks([websocket_init/2]).
-callback websocket_handle({text | binary | ping | pong, binary()}, Req, State) -callback websocket_handle({text | binary | ping | pong, binary()}, Req, State)
-> {ok, Req, State} -> {ok, Req, State}
| {ok, Req, State, hibernate} | {ok, Req, State, hibernate}

View file

@ -393,12 +393,27 @@ websocket(_) ->
Msg1 -> Msg1 ->
exit({connection_failed, Msg1}) exit({connection_failed, Msg1})
end, end,
%% Check that we receive the message sent on timer on init.
receive
{gun_ws, Pid, {text, <<"Hello!">>}} ->
ok
after 2000 ->
exit(timeout)
end,
%% Check that we receive subsequent messages sent on timer.
receive
{gun_ws, Pid, {text, <<"How' you doin'?">>}} ->
ok
after 2000 ->
exit(timeout)
end,
%% Check that we receive the echoed message.
gun:ws_send(Pid, {text, <<"hello">>}), gun:ws_send(Pid, {text, <<"hello">>}),
receive receive
{gun_ws, Pid, {text, <<"That's what she said! hello">>}} -> {gun_ws, Pid, {text, <<"That's what she said! hello">>}} ->
ok; ok
Msg2 -> after 500 ->
exit({receive_failed, Msg2}) exit(timeout)
end, end,
gun:ws_send(Pid, close) gun:ws_send(Pid, close)
after after