-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
49 lines (45 loc) · 1.28 KB
/
main.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
class Chat {
constructor(ws, input, output) {
this.ws = ws;
this.input = input;
this.output = output;
this.addListeners();
}
addListeners() {
this.ws.addEventListener('open', this.onOpen);
this.ws.addEventListener('message', this.onMessage);
this.ws.addEventListener('error', this.onError);
this.ws.addEventListener('close', this.onClose);
this.input.addEventListener('keydown', this.onKeyDown);
}
onOpen = () => console.log('socket opened');
onMessage = message => {
this.showMessage(message.data);
};
onError = error => {
this.showMessage('connection error, check console for more details');
console.log('connection error', error);
};
onClose = () => {
this.showMessage('connection closed');
};
onKeyDown = event => {
if (event.code === 'Enter') {
event.preventDefault();
this.sendMessage();
}
};
sendMessage() {
this.ws.send(this.input.value);
this.input.value = '';
}
showMessage(text) {
this.output.value += text + '\n';
}
}
window.addEventListener('load', async () => {
const ws = new WebSocket(`ws://${location.hostname}:8081/ws`);
const input = document.getElementById('input');
const output = document.getElementById('output');
window.chat = new Chat(ws, input, output);
});