Skip to content
This repository
Newer
Older
100644 111 lines (106 sloc) 4.489 kb
dce39c9b »
2011-12-03 added support for session access from websockets
1 % ==========================================================================================================
2 % MISULTIN - Websocket Sessions Example.
3 %
4 % >-|-|-(°>
5 %
6 % Copyright (C) 2011, Roberto Ostinelli <roberto@ostinelli.net>
7 % All rights reserved.
8 %
9 % BSD License
10 %
11 % Redistribution and use in source and binary forms, with or without modification, are permitted provided
12 % that the following conditions are met:
13 %
14 % * Redistributions of source code must retain the above copyright notice, this list of conditions and the
15 % following disclaimer.
16 % * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
17 % the following disclaimer in the documentation and/or other materials provided with the distribution.
18 % * Neither the name of the authors nor the names of its contributors may be used to endorse or promote
19 % products derived from this software without specific prior written permission.
20 %
21 % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
22 % WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23 % PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
24 % ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
25 % TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 % HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 % NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 % POSSIBILITY OF SUCH DAMAGE.
29 % ==========================================================================================================
30 -module(misultin_websocket_sessions_example).
31 -export([start/1, stop/0]).
32
33 % start misultin http server
34 start(Port) ->
35 misultin:start_link([{port, Port}, {loop, fun(Req) -> handle_http(Req, Port) end}, {ws_loop, fun(Ws) -> handle_websocket(Ws) end}]).
36
37 % stop misultin
38 stop() ->
39 misultin:stop().
40
41 % callback on request received
42 handle_http(Req, Port) ->
43 % get session info
44 {SessionId, _SessionState} = Req:session(),
45 % save user's peer_addr and a resetted counter as session's state. a more complex state can easily be saved here, such as proplist()
46 Req:save_session_state(SessionId, {Req:get(peer_addr), 1}),
47 % output
48 Req:ok([{"Content-Type", "text/html"}],
49 ["
50 <html>
51 <head>
52 <script type=\"text/javascript\">
53 function addStatus(text){
54 var date = new Date();
55 document.getElementById('status').innerHTML = document.getElementById('status').innerHTML + date + \": \" + text + \"<br>\";
56 }
57 function ready(){
58 var ws;
59 if (\"WebSocket\" in window) {
60 ws = new WebSocket(\"ws://localhost:", erlang:integer_to_list(Port) ,"/service\");
61 } else if (\"MozWebSocket\" in window) {
62 ws = new MozWebSocket(\"ws://localhost:", erlang:integer_to_list(Port) ,"/service\");
63 }
64 if (ws) {
65 // browser supports websockets
66 ws.onopen = function() {
67 // websocket is connected
68 addStatus(\"websocket connected!\");
69 // send hello data to server.
70 ws.send(\"hello server!\");
71 addStatus(\"sent message to server: 'hello server'!\");
72 };
73 ws.onmessage = function (evt) {
74 var receivedMsg = evt.data;
75 addStatus(\"server sent the following: '\" + receivedMsg + \"'\");
76 };
77 ws.onclose = function() {
78 // websocket was closed
79 addStatus(\"websocket was closed\");
80 };
81 } else {
82 // browser does not support websockets
83 addStatus(\"sorry, your browser does not support websockets.\");
84 }
85 }
86 </script>
87 </head>
88 <body onload=\"ready();\">
89 <div id=\"status\"></div>
90 </body>
91 </html>"]).
92
93 % callback on received websockets data
94 handle_websocket(Ws) ->
95 % get session info
96 {SessionId, {UserPeerAddr, Count}} = Ws:session(),
97 receive
98 {browser, Data} ->
99 Ws:send(["received '", Data, "'"]),
100 handle_websocket(Ws);
101 _Ignore ->
102 handle_websocket(Ws)
103 after 5000 ->
104 % increase pushed counter and save new sessin state
105 Ws:save_session_state(SessionId, {UserPeerAddr, Count + 1}),
106 % build push message
107 Pushmessage = lists:flatten(io_lib:format("pushed ~p time(s) for user with session IP: ~p", [Count, UserPeerAddr])),
108 Ws:send(Pushmessage),
109 handle_websocket(Ws)
110 end.
Something went wrong with that request. Please try again.