-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
51 lines (38 loc) · 1.21 KB
/
client.js
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
const socket = new WebSocket('ws://localhost:8080');
const messageList = document.getElementById('messageList');
const messageInput = document.getElementById('messageInput');
socket.addEventListener('open', (event) => {
console.log('Connected to WebSocket server');
});
socket.addEventListener('message', (event) => {
console.log(`Received from server: ${event.data}`);
appendToList(event.data);
});
socket.addEventListener('close', (event) => {
if (event.wasClean) {
console.log('Connection closed cleanly');
} else {
console.error('Connection abruptly closed');
}
});
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
function appendToList(message) {
const listItem = document.createElement('li');
listItem.textContent = message;
messageList.appendChild(listItem);
messageList.scrollTop = messageList.scrollHeight;
}
function sendMessage() {
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
appendToList(message);
}
messageInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
sendMessage();
}
});