-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.html
84 lines (71 loc) · 2.2 KB
/
client.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html>
<html lang="en">
<head>
<title>Websocket Example Client</title>
<style>
body {
font-family: sans-serif;
margin-top: 60px;
}
#status {
padding: .5em;
top: 0;
position: absolute;
width: 98%;
}
</style>
</head>
<body>
<p>Your client ID: <code id="uuid"></code></p>
<button onclick="btnClick()">Say Hello to other Clients</button>
<p id="status"></p>
</body>
</html>
<script>
const $uuid = document.getElementById('uuid'),
$status = document.getElementById('status');
//function to generate a unique id for the client.
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const id = uuidv4();
const url = 'ws://localhost:8080'; // as defined in server.js
const connection = new WebSocket(url);
connection.onopen = () => {
console.log("Connection to Websocket Server established!");
};
connection.onmessage = (e) => {
let data = JSON.parse(e.data);
if(data.senderId === id) {
$status.innerText = 'Your message was sent.';
} else {
$status.innerHTML = 'Received Message from ' + data.senderId + ':<strong>' + data.body + '</strong>';
}
};
connection.onclose = () => {
console.log("Connection closed!");
};
connection.onerror = (error) => {
console.log('An error occured:' + error);
};
function btnClick() {
connection.send(JSON.stringify({
senderId: id,
body: "Hello from a happy Client!"
}));
}
// Check if websocket connection is established after 1.5s
window.setTimeout(function () {
if (3 === connection.readyState) {
$status.innerText = 'Connection failed!';
$status.style.backgroundColor = 'red';
} else {
$status.innerText = 'Connection OK';
$status.style.backgroundColor = '#83e283';
$uuid.innerText = id;
}
}, 1500);
</script>