-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
53 lines (47 loc) · 1.36 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
<!-- index.html -->
<!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>Web Socket Client | Erick Wendel</title>
</head>
<body>
<!-- 1 -->
<p>Messages</p>
<output id="messages"></output>
<script>
const messages = document.getElementById("messages");
// 2
const socket = new WebSocket("ws://localhost:1337");
// 3
socket.onopen = (event) => {
console.log("WebSocket is connected!");
const id = Math.round(Math.random() * 100);
console.log("sending...", id);
const data = JSON.stringify({
id,
name: `[${id}] Erick Wendel`,
address: {
street: "my street",
number: 20 * id,
},
profession: "developer",
});
socket.send(data);
};
// 4
socket.onmessage = (msg) => {
const message = msg.data;
console.log("I got a message!", message);
messages.innerHTML += `<br /> ${message}`;
};
// 5
socket.onerror = (error) => console.log("WebSocket error", error);
// 6
socket.onclose = (event) =>
console.log("Disconnected from the WebSocket server");
</script>
</body>
</html>