-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
51 lines (43 loc) · 1.54 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Just test websockets</h2>
<input type="text" placeholder="type message to server" />
<button id="send">Send</button>
<button id="close-ws">Close connection</button>
<script>
const ws = new WebSocket('ws://localhost:8073');
// close ws
function closeConnection() {
console.log('trying to close ws');
ws.close(1000, 'Closed by button click');
}
// send message to server
function sendMessage() {
console.log('trying to send a message');
const input = document.querySelector('input');
ws.send(input?.value);
}
// add listener when ws open
ws.addEventListener('open', () => {
console.log("I'm connected");
});
// add listener for every message from server
ws.addEventListener('message', ({data}) => {
console.log("Message from server: " + data);
});
// add listener for click by close button
const btnClose = document.querySelector('#close-ws');
btnClose.addEventListener('click', closeConnection);
// add listener for click by send button
const btnSend = document.querySelector('#send');
btnSend.addEventListener('click', sendMessage);
</script>
</body>
</html>