-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
50 lines (41 loc) · 1.34 KB
/
Copy pathindex.js
File metadata and controls
50 lines (41 loc) · 1.34 KB
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
const WEB_SOCKET_SERVER = 'wss://websocket-echo.glitch.me'
const STATUS = {
0: 'CONNECTING',
1: 'OPEN',
2: 'CLOSING',
3: 'CLOSED'
}
const socket = new WebSocket(WEB_SOCKET_SERVER)
const statusElement = document.getElementById('status')
statusElement.innerText = STATUS[socket.readyState]
/**
* ? WEBSOCKET EVENTS
*/
// Fired when a connection with a WebSocket is opened. Also available via the onopen property.
socket.addEventListener("open", (event) => {
statusElement.innerText = STATUS[event.target.readyState]
})
// Fired when data is received through a WebSocket. Also available via the onmessage property.
socket.addEventListener('message', (event) => {
const messageElement = document.getElementById('messages')
messageElement.innerHTML += event.data + '<br/>'
})
socket.addEventListener('close', (event) => {
statusElement.innerText = STATUS[event.target.readyState]
})
/**
* ? FORMS
*/
const chatForm = document.getElementById('chat-form')
const connectionForm = document.getElementById('close-form')
chatForm.addEventListener('submit' , event => {
event.preventDefault()
const message = document.getElementById('message')
socket.send(message.value)
message.value = ''
})
connectionForm.addEventListener('submit' , event => {
event.preventDefault()
// Closes the connection.
socket.close()
})