-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
102 lines (92 loc) · 3.05 KB
/
index.html
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
93
94
95
96
97
98
99
100
101
102
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>XHR Server Stream Example</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
#messages {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
height: 300px;
overflow-y: auto;
background-color: #f9f9f9;
}
.message {
padding: 5px;
margin: 5px 0;
background-color: #e0f7fa;
border-radius: 5px;
}
button {
margin-top: 20px;
padding: 10px 20px;
background-color: #ff5733;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #c44d2d;
}
</style>
</head>
<body>
<h1>XHR Server Stream Example</h1>
<div id="messages"></div>
<button id="stopButton">Stop Stream</button>
<script>
// Select the div where messages will be displayed
const messagesDiv = document.getElementById("messages");
const stopButton = document.getElementById("stopButton");
let xhr; // Declare the XMLHttpRequest variable
// Function to start the XHR stream
function startStream() {
xhr = new XMLHttpRequest();
xhr.open("GET", "/events", true);
xhr.setRequestHeader("Cache-Control", "no-cache");
// Response is processed as text
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.LOADING && xhr.status === 200) {
// Split the response into individual messages
const messages = xhr.responseText.split("\n");
for (let i = 0; i < messages.length; i++) {
if (messages[i].trim() !== "") {
const messageDiv = document.createElement("div");
messageDiv.classList.add("message");
messageDiv.textContent = messages[i].trim();
// Append the new message to the messages div
messagesDiv.appendChild(messageDiv);
// Scroll to the bottom of the div to show the latest message
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
}
}
};
// Handle errors and disconnection
xhr.onerror = function () {
console.error("Error occurred during the stream.");
};
xhr.send(); // Send the request to start the stream
}
// Function to stop the XHR stream
function stopStream() {
if (xhr) {
xhr.abort(); // Terminate the XHR connection
stopButton.disabled = true; // Disable the button after stopping the stream
stopButton.textContent = "Stream Stopped"; // Change button text
}
}
// Add an event listener to the stop button
stopButton.addEventListener("click", stopStream);
// Start the XHR stream
startStream();
</script>
</body>
</html>