-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.html
More file actions
92 lines (80 loc) · 2.74 KB
/
Copy pathclient.html
File metadata and controls
92 lines (80 loc) · 2.74 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head>
<title>Websockets and HTTP Requests Demo</title>
</head>
<body>
<h1>Websockets and HTTP Requests Demo</h1>
<h2>WebSocket Communication</h2>
<div id="websocketStatus">WebSocket Status: Not connected</div>
<button onclick="connectWebSocket()">Connect</button>
<button onclick="disconnectWebSocket()">Disconnect</button>
<br><br>
<div id="websocketMessages"></div>
<input type="text" id="websocketInput" placeholder="Enter a message">
<button onclick="sendWebSocketMessage()">Send</button>
<h2>HTTP Requests</h2>
<button onclick="sendGetRequest()">Send GET Request</button>
<button onclick="sendPostRequest()">Send POST Request</button>
<div id="httpResponse"></div>
<script>
// WebSocket variables
let socket;
function connectWebSocket() {
socket = new WebSocket("ws://localhost:9000/ws");
socket.onopen = function (event) {
document.getElementById("websocketStatus").innerHTML =
"WebSocket Status: Connected";
};
socket.onmessage = function (event) {
document.getElementById("websocketMessages").innerHTML +=
"<p>" + event.data + "</p>";
};
socket.onclose = function (event) {
document.getElementById("websocketStatus").innerHTML =
"WebSocket Status: Not connected";
};
}
function disconnectWebSocket() {
if (socket) {
socket.close();
}
}
function sendWebSocketMessage() {
const message = document.getElementById("websocketInput").value;
socket.send(message);
document.getElementById("websocketInput").value = "";
}
// HTTP Request functions
function sendGetRequest() {
fetch("http://localhost:9000/get")
.then((response) => response.json())
.then((data) => {
document.getElementById("httpResponse").innerHTML =
"<pre>" + JSON.stringify(data, null, 2) + "</pre>";
})
.catch((error) => {
console.error("Error:", error);
});
}
function sendPostRequest() {
const data = { message: "Hello, server!" };
fetch("http://localhost:9000/post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
document.getElementById("httpResponse").innerHTML =
"<pre>" + JSON.stringify(data, null, 2) + "</pre>";
})
.catch((error) => {
console.error("Error:", error);
});
}
</script>
</body>
</html>