-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
92 lines (79 loc) · 2.9 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Websocket Chat Testing</title>
<style>
#chat {
width: 600px;
height: 600px;
background: #ccc;
margin-bottom:10px;
padding: 10px;
}
</style>
</head>
<body>
<script>
document.addEventListener("DOMContentLoaded", function () {
const chat = document.getElementById("chat");
const connectButton = document.getElementById("connect");
const sendButton = document.getElementById("send");
const to = document.getElementById("to");
const text = document.getElementById("text");
const token = document.getElementById("token");
connectButton.onclick = function () {
const ws = new WebSocket("ws://127.0.0.1:9002?token=" + token.value);
ws.onmessage = function (message) {
try {
let messageData = JSON.parse(message.data);
let msg = messageData.data;
let type = messageData.type;
let p = document.createElement("p");
if (type === 'message') {
let msgHeader;
if (!msg.to) {
msgHeader = "<b>" + msg.from + "</b>";
} else {
msgHeader = "<b>" + msg.from + " -> " + msg.to + "</b>";
}
p.innerHTML = msgHeader + " [" + msg.date_time + "]: " + msg.text;
} else if (type === 'join') {
p.innerHTML = msg.user + ' has joined';
}
chat.appendChild(p);
} catch (e) {
console.error(e);
}
// console.log('message', message);
};
ws.onerror = function (error) {
console.error(error);
};
ws.onopen = function () {
console.log("connected to webscoket");
chat.innerHTML = '';
sendButton.onclick = function () {
let message = {
to: to.value,
text: text.value
};
console.log(message);
ws.send(JSON.stringify(message));
}
}
}
})
</script>
<input id="token" type="text">
<button id="connect">Connect</button>
<br><br>
<div id="chat">
</div>
<div>
To: <input type="text" id="to">
Text: <input type="text" id="text">
<button id="send">Submit</button>
</div>
</body>
</html>