-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_json_tester.js
More file actions
75 lines (68 loc) · 2.16 KB
/
websocket_json_tester.js
File metadata and controls
75 lines (68 loc) · 2.16 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// HTML elements this program interacts with
const url_input = document.querySelector("#url_input");
const body_input = document.querySelector("#body_input");
const output = document.querySelector("#output");
// variable for websocket
let socket = null;
function add_paragraf_to_output(paragraf) {
output.innerHTML += paragraf;
output.innerHTML += "\n\n";
output.scrollTop = output.scrollHeight;
}
// socket event actions
function socket_ononopen(event) {
add_paragraf_to_output("Successfully connected!");
}
function socket_onmessage(event) {
data = JSON.parse(event.data);
message = "socket_onmessage:\n" + JSON.stringify(data, null, 4);
add_paragraf_to_output(message);
}
function socket_onerror(event) {
message = "socket_onerror:\n" + event;
add_paragraf_to_output(message);
console.log("socket_onerror:\n", event);
}
function socket_onclose(event) {
message = "socket_onclose:\n" + event;
add_paragraf_to_output(message);
console.log("socket_onclose:\n", event);
socket = null;
}
// when you click CONNECT button
document.querySelector("#connect").onclick = function(event) {
if (socket != null) { // silently closes the previous socket
socket.onclose = null;
socket.close();
}
message = "Connecting to " + url_input.value
add_paragraf_to_output(message);
try {
socket = new WebSocket(url_input.value);
// passing on the socket functions
socket.onopen = socket_ononopen;
socket.onmessage = socket_onmessage;
socket.onerror = socket_onerror;
socket.onclose = socket_onclose;
} catch (error) {
socket = null;
add_paragraf_to_output(error);
}
}
// when you click SEND button
document.querySelector("#send").onclick = function(event) {
if (socket == null) {
alert("First you need to connect to a WebSocket!");
return;
}
if (socket.readyState == WebSocket.CONNECTING) {
alert("WebSocket is still connecting!");
return;
}
try {
body = JSON.parse(body_input.value);
socket.send(JSON.stringify(body));
} catch (error) {
add_paragraf_to_output(error);
}
}