/
demo.clj
125 lines (107 loc) · 3.62 KB
/
demo.clj
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
(ns rooms.demo
(:use [compojure.route :only [files not-found]]
[compojure.core :only [defroutes GET]]
org.httpkit.server)
(:require [rooms.core :as rooms]
[ring.middleware.defaults :refer [wrap-defaults api-defaults]]))
(def demo-registry (atom (rooms/empty-room-registry 2)))
(def test-page (atom "
<html>
<head>
<title>Server Test</title>
<style>
* {
font-family: monospace;
}
</style>
</head>
<body>
<h1>Just testing the server...</h1>
<h2>State:</h2>
<pre id='state'></pre>
<h2>Messages Seen:</h2>
<ul id='messages'></ul>
<script src='https://code.jquery.com/jquery-3.4.1.min.js'
integrity='sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=' crossorigin='anonymous'></script>
<script crossorigin src='https://unpkg.com/@msgpack/msgpack'></script>
<script>
const ws = connect('demo', {
onConnect() {
setTimeout(() => {
this.send(JSON.stringify({ greeting: 'hello', from: navigator.userAgent }));
}, 1000);
},
onMessage(msg) {
console.log(msg);
let contents = msg.data;
let decoded = parseMsgpackOrJSON(msg);
$('#messages').append($(`<li><pre>${JSON.stringify(decoded)}</pre></li>`))
$('#state').text(JSON.stringify(decoded.state, null, 2))
}
});
function connect(roomId, {onConnect, onMessage}) {
const ws = new WebSocket('ws://localhost:8080/room/' + roomId);
ws.onopen = onConnect.bind(ws);
ws.onmessage = onMessage.bind(ws);
return ws;
}
function blobBytes(blob) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.addEventListener('loadend', () => {
const buf = reader.result;
const bz = new Uint8Array(buf, 0, buf.byteLength);
resolve(bz);
});
reader.readAsArrayBuffer(blob);
});
}
function parseMsgpackOrJSON(msg) {
if (msg.data instanceof Blob) {
blobBytes(msg.data).then(bz => {
const decoded = MessagePack.decode(bz);
console.log('Decoded MessagePack: ', decoded);
return decoded;
});
}
else if (typeof msg.data === 'string') {
const decoded = JSON.parse(msg.data);
console.log('Decoded JSON: ', decoded);
return decoded;
}
else {
console.error('Could not decode message: ', msg);
throw new Error('Could not decode message');
}
}
</script>
</body>
</html>
"))
(def create-room! (partial rooms/create-room! demo-registry))
(defn- set-test-port!
[port] (swap! test-page clojure.string/replace #"localhost:\d*" (str "localhost:" port)))
(defn- get-ip
[req]
(or (get-in req [:headers "x-forwarded-for"])
(:remote-addr req)))
(defroutes demo-routes
(GET "/" [_ :as req] (identity {:status 200 :headers {"Content-Type" "text/html"} :body @test-page}))
(GET "/room/:id" [id encoding :as req]
(let [user {:id (str (System/currentTimeMillis) "-" (get-ip req)) :joined-at (System/currentTimeMillis)}]
(rooms/connect! demo-registry id user req encoding)))
(not-found "<p>Page not found.</p>"))
(defn- start-server [opts]
(do (set-test-port! (:port opts))
(run-server
(wrap-defaults demo-routes api-defaults)
opts)))
(def stopper (atom nil))
(defn start [& opts]
(let [realopts (merge {:port 8080} (or (first opts) {}))]
(do (create-room! "demo"
(fn [s m] (do (println "RCV:" m) (assoc s :last-message m)))
(fn [s uid] s))
(reset! stopper (start-server realopts))
(println "Started demo server on port " (:port realopts)))))
(defn stop [] (@stopper))