-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscript.js
74 lines (64 loc) · 1.9 KB
/
script.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
WebSocket connection Script
Uses standard W3C WebSocket API, not socket.io API
Connects to postmans's test server at
wss://ws.postman-echo.com/raw
created 7 Jan 2021
modified 4 Sep 2022
by Tom Igoe
*/
const serverURL = 'wss://ws.postman-echo.com/raw';
let socket;
// variables for the DOM elements:
let incomingSpan;
let outgoingText;
let connectionSpan;
let connectButton;
function setup() {
// get all the DOM elements that need listeners:
incomingSpan = document.getElementById('incoming');
outgoingText = document.getElementById('outgoing');
connectionSpan = document.getElementById('connection');
connectButton = document.getElementById('connectButton');
// set the listeners:
outgoingText.addEventListener('change', sendMessage);
connectButton.addEventListener('click', changeConnection);
openSocket(serverURL);
}
function openSocket(url) {
// open the socket:
socket = new WebSocket(url);
socket.addEventListener('open', openConnection);
socket.addEventListener('close', closeConnection);
socket.addEventListener('message', readIncomingMessage);
}
function changeConnection(event) {
// open the connection if it's closed, or close it if open:
if (socket.readyState === WebSocket.CLOSED) {
openSocket(serverURL);
} else {
socket.close();
}
}
function openConnection() {
// display the change of state:
connectionSpan.innerHTML = "true";
connectButton.value = "Disconnect";
}
function closeConnection() {
// display the change of state:
connectionSpan.innerHTML = "false";
connectButton.value = "Connect";
}
function readIncomingMessage(event) {
// display the incoming message:
incomingSpan.innerHTML = event.data;
}
function sendMessage() {
//if the socket's open, send a message:
if (socket.readyState === WebSocket.OPEN) {
socket.send(outgoingText.value);
}
}
// add a listener for the page to load:
window.addEventListener('load', setup);