-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
59 lines (51 loc) · 1.76 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Shrek App</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<h1>Open your browser console to see the logs and details of API you can use to talk to the server.</h1>
<script>
let connection;
function displayHelp() {
console.log('Available channels:')
console.log('* /chat');
console.log('* /travel/status');
console.log('Available commands:')
console.log('- listen: Establish a connection with the server at a given path.')
console.log(' Usage: listen(channelName)');
console.log(` Example: listen('/chat')`);
console.log('- send: Send a message to the server at a currently connected path.')
console.log(' Usage: send(message)');
console.log(` Example: send({ greet: 'Hello from client' })`);
}
function listen(path) {
const url = new URL(path, 'ws://localhost').toString()
connection = new WebSocket(url)
connection.onerror = error => {
console.log(`WebSocket error: ${error}`)
}
connection.onopen = () => {
console.log('Connected to server');
}
connection.onmessage = e => {
console.log('Server says:', e.data)
}
}
function send(message) {
if (!connection) {
console.error('You have to call listen(channelName) first. See the list of available commands and below.');
displayHelp();
return;
}
let msg = message;
if (typeof msg === 'object') msg = JSON.stringify(msg);
connection.send(msg);
console.info('Hint: check out the server logs to see your message.');
}
displayHelp();
</script>
</body>
</html>