blob: 3b3d4ced4782fe44f4645dfdb8ee6f1ee0c0aef3 (
plain)
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
|
<!doctype html>
<html>
<head>
<title>WS Test</title>
<style>
.b {
border-bottom: 1px solid black;
}
</style>
</head>
<body style='background: black; color: white'>
<div id='cons'>connected</div><br>
<button onclick='test_connection()'>Launch</button><br>
<span>Server address: </span><input id='addr'></input>
<div align='right'><span>Message</span><input id='msg'></input> <button onclick='send_text()'>Send</button></div>
<div id='chat' style='background: rgb(20, 20, 20); padding-left: 20px; margin: 40px' />
</body>
<script>
function get_addr() {
return document.getElementById('addr').value;
}
function test_connection() {
let a = 'ws://' + get_addr();
add_text('create a new connection at "' + a + '"');
ws = new WebSocket(a, 'tuesday');
ws.addEventListener('open', function (event) {
add_text('connection established');
toggle_connected(true);
// send token
ws.send('42');
});
ws.addEventListener('error', function (event) {
add_text('ws error occured: "' + event + '"');
toggle_connected(false);
});
ws.addEventListener('close', function (event) {
add_text('ws is closed now');
toggle_connected(false);
});
ws.addEventListener('message', function (event) {
add_text('got ws message: "' + event.data + '"');
});
}
function send_text() {
let msg = document.getElementById('msg').value;
ws.send(msg);
add_text('sent message: "' + msg + '"');
}
function add_text(text, color='white') {
let c = document.getElementById('chat');
let n = document.createElement('span');
n.setAttribute('class', 'b');
n.style = 'color: ' + color;
n.textContent = (new Date()).toTimeString().substring(0, 8) + '|> '+ text;
c.appendChild(n);
c.appendChild(document.createElement('br'));
}
function toggle_connected(con) {
let c = document.getElementById('cons');
if (con) {
c.style = 'background: green'
c.textContent = 'connected';
} else {
c.style = 'background: red'
c.textContent = 'not connected';
}
}
toggle_connected(false);
add_text("JS loaded");
</script>
</html>
|