-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsockets_example_endpoint.yaws
69 lines (64 loc) · 2.33 KB
/
websockets_example_endpoint.yaws
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<erl>
out(A) ->
case get_upgrade_header(A#arg.headers) of
undefined ->
{content, "text/plain", "You're not a web sockets client! Go away!"};
"WebSocket" ->
spawn_ws_owner();
"websocket" ->
spawn_ws_owner()
end.
spawn_ws_owner() ->
io:format("Spawning websocket owner~n",[]),
WebSocketOwner = spawn(fun() -> websocket_owner() end),
{websocket, WebSocketOwner, passive}.
websocket_owner() ->
receive
{ok, WebSocket, ProtocolVersion} ->
%% This is how we read messages (plural!!) from websockets on passive mode
case yaws_api:websocket_receive(WebSocket, ProtocolVersion) of
{error,closed} ->
io:format("The websocket got disconnected right from the start. "
"This wasn't supposed to happen!!~n");
{ok, Messages} ->
case Messages of
[<<"client-connected">>] ->
yaws_api:websocket_setopts(WebSocket, [{active, true}]),
echo_server(WebSocket, ProtocolVersion);
Other ->
io:format("websocket_owner got: ~p. Terminating~n", [Other])
end
end;
_ -> ok
end.
echo_server(WebSocket, ProtocolVersion) ->
receive
{tcp, WebSocket, DataFrame} ->
Data = yaws_api:websocket_unframe_data(ProtocolVersion, DataFrame),
io:format("Got data from Websocket: ~p~n", [Data]),
yaws_api:websocket_send(WebSocket, ProtocolVersion, Data),
echo_server(WebSocket, ProtocolVersion);
{tcp_closed, WebSocket} ->
io:format("Websocket closed. Terminating echo_server...~n");
Any ->
io:format("echo_server received msg:~p~n", [Any]),
echo_server(WebSocket, ProtocolVersion)
end.
get_upgrade_header(#headers{other=L}) ->
lists:foldl(fun({http_header,_,K0,_,V}, undefined) ->
K = case is_atom(K0) of
true ->
atom_to_list(K0);
false ->
K0
end,
case string:to_lower(K) of
"upgrade" ->
V;
_ ->
undefined
end;
(_, Acc) ->
Acc
end, undefined, L).
</erl>