-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
68 lines (64 loc) · 2.18 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
60
61
62
63
64
65
66
67
68
<html>
<head>
</head>
<body>
<h1>Basic WebSockets Example</h1>
<h2>The Server Says:</h2>
<h2></h2>
<h3></h3>
<button>Send message to server</button>
<button>Close WebSocket</button>
<button>Test close event errors</button>
<script>
'use strict';
// Open WebSocket on a new port.
var host = window.document.location.host.replace(/:.*/, '');
var port = 8000;
var ws = new WebSocket('ws://' + host + ':' + port);
function printStatus(status) {
status += '<br>' +
'readyState: ' + ws.readyState + '<br>' +
'bufferedAmount: ' + ws.bufferedAmount + '<br>' +
'extensions: ' + ws.extensions + '<br>' +
'protocol: ' + ws.protocol + '<br>' +
'binaryType: ' + ws.binaryType;
document.querySelector('h3').innerHTML = status;
}
// WebSocket Events.
ws.addEventListener('message', function print(messageEvent) {
var message = messageEvent.data;
document.querySelectorAll('h2')[1].innerHTML = message;
});
ws.addEventListener('open', function (event) {
printStatus('The connection is open.');
});
ws.addEventListener('close', function (event) {
printStatus('The connection is closed.');
});
ws.addEventListener('error', function (event) {
printStatus('There was an error.');
});
// WebSocket Methods.
document.querySelector('button').addEventListener('click', function () {
ws.send('Hi server, I am the client.');
});
document.querySelectorAll('button')[1].addEventListener('click', function () {
ws.close();
});
document.querySelectorAll('button')[2].addEventListener('click', function () {
var invalidCode = 1001;
var invalidReason = '♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥';
try {
ws.close(invalidCode);
} catch (error) {
document.body.innerHTML += '<p>' + error + '</p>';
}
try {
ws.close(1000, invalidReason);
} catch (error) {
document.body.innerHTML += '<p>' + error + '</p>';
}
});
</script>
</body>
</html>