-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
51 lines (37 loc) · 1.32 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
<h1>Chat</h1>
<div id="chat"></div>
<input type="text" id="username" placeholder="username"/>
<input type="text" id="message" placeholder="message"/>
<button id="send" title="Send!">Send Message</button>
<script>
const sendBtn = document.getElementById('send');
const chat = document.getElementById('chat');
const showMessage = (socketMessages) => {
const messages = JSON.parse(socketMessages);
for (const message of messages) {
const line = document.createElement('div');
line.innerHTML = `<p>${message.username}: ${message.message}</p>`;
chat.appendChild(line);
message.value = '';
}
};
const ws = new WebSocket('ws://localhost:6663/chat');
ws.onopen = () => {
console.log('Connection opened!');
};
ws.onmessage = ({ data }) => showMessage(data);
ws.onclose = (event) => {
console.log(`Code: ${event.code} reason: ${event.reason}`);
};
sendBtn.onclick = () => {
if (!ws) {
showMessage('No WebSocket connection :(');
return;
}
const message = document.getElementById('message').value;
const username = document.getElementById('username').value;
const sendMessage = JSON.stringify([{ username, message }]);
ws.send(sendMessage);
showMessage(sendMessage);
};
</script>