-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
89 lines (74 loc) · 2.44 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
WebSocket Client Script for Command Execution and Status Updates
This script connects to the server using WebSockets to send and receive
data related to command execution (ping, mtr, traceroute). The WebSocket
connection dynamically sends the command along with the target input
provided by the user.
Key Features:
- Initializes WebSocket connection to the server on page load.
- Manages buttons' state to prevent sending multiple commands at once.
- Listens for incoming data from the server, displays it in real-time, and
handles connection closure.
- Handles errors and WebSocket reconnections.
Functions:
- toggleButtons: Enables/disables command buttons based on whether a
command is running.
- connectWebSocket: Establishes a WebSocket connection and defines event
handlers for open, message, close, and error events.
- send: Sends the selected command (ping, mtr, or traceroute) to the server
and updates the UI accordingly.
*/
let ws;
let commandRunning = false;
const output = document.getElementById('output');
const target = document.getElementById('target');
const ping = document.getElementById('ping');
const mtr = document.getElementById('mtr');
const traceroute = document.getElementById('traceroute');
function toggleButtons(disabled) {
ping.disabled = disabled;
mtr.disabled = disabled;
traceroute.disabled = disabled;
}
function connectWebSocket() {
const prot = window.location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(`${prot}://${window.location.hostname}`);
ws.onopen = () => {
console.log('WebSocket connection opened');
};
ws.onmessage = (event) => {
if (event.data == 'close') {
commandRunning = false;
toggleButtons(false);
return;
}
output.classList.remove('d-none');
output.textContent += event.data;
};
ws.onclose = () => {
console.log('WebSocket connection closed');
commandRunning = false;
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
commandRunning = false;
};
}
function send(commandType) {
if (commandRunning) {
return;
}
if (!target.value) {
target.focus();
return;
}
toggleButtons(true);
commandRunning = true;
output.textContent = '';
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(`${commandType} ${target.value}`);
} else {
output.textContent = 'WebSocket connection is not open';
}
}
window.onload = connectWebSocket;