]> code.delx.au - gnu-emacs-elpa/blob - packages/web-server/examples/009-web-socket.el
Merge commit '0cda39255827f283e7578cd469ae42daad9556a2' from js2-mode
[gnu-emacs-elpa] / packages / web-server / examples / 009-web-socket.el
1 ;;; web-sockets.el --- communicate via web-sockets
2 ;; Copyright (C) 2014 Free Software Foundation, Inc.
3
4 (lexical-let* ((web-socket-port 9009)
5 (web-socket-page
6 (format "<html>
7 <head>
8 <script type=\"text/javascript\">
9 var ws;
10 function connect(){
11 ws = new WebSocket(\"ws://localhost:%d/\");
12
13 ws.onopen = function() { alert(\"connected\"); };
14 ws.onmessage = function(msg) { alert(\"server: \" + msg.data); };
15 ws.onclose = function() { alert(\"connection closed\"); };
16 }
17
18 function message(){ ws.send(\"foo\"); }
19
20 function close(){ ws.close(); };
21 </script>
22 </head>
23 <body>
24 <ol>
25
26 <li>Press \"connect\" to initialize the web socket connection to
27 the server. The server will complete the web socket
28 handshake at which point you'll see an alert with the text
29 \"connected\".</li>
30
31 <li>Press \"message\" to send the string \"foo\" to the server.
32 The server will reply with the text \"you said: foo\" which
33 you will see in an alert as \"server: you said: foo\".</li>
34
35 <li>Press \"close\" to close the connection. After the server
36 responds with a close frame you will see an alert with the
37 text \"connection closed\".</li>
38
39 </ol>
40 <a href=\"javascript:connect()\">connect</a>
41 <a href=\"javascript:message()\">message</a>
42 <a href=\"javascript:close()\">close</a>
43 </body>
44 </html>" web-socket-port)))
45 (ws-start
46 (lambda (request)
47 (with-slots (process headers) request
48 ;; if a web-socket request, then connect and keep open
49 (if (ws-web-socket-connect request
50 (lambda (proc string)
51 (process-send-string proc
52 (ws-web-socket-frame (concat "you said: " string)))))
53 (prog1 :keep-alive (setq my-connection process))
54 ;; otherwise send the index page
55 (ws-response-header process 200 '("Content-type" . "text/html"))
56 (process-send-string process web-socket-page))))
57 web-socket-port))