-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsse.html
53 lines (48 loc) · 1.46 KB
/
sse.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
<!DOCTYPE html>
<html>
<head>
<title>SSE Demo</title>
</head>
<body>
<h1>Server-Sent Events Demo</h1>
<div>
<h2>Send Message</h2>
<input type="text" id="messageText" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
</div>
<div>
<h2>Received Messages:</h2>
<ul id="messages"></ul>
</div>
<script>
// Connect to SSE endpoint
const eventSource = new EventSource('/sse');
// Handle incoming messages
eventSource.onmessage = function(event) {
const messages = document.getElementById('messages');
const message = document.createElement('li');
message.textContent = event.data;
messages.appendChild(message);
};
// Handle errors
eventSource.onerror = function(error) {
console.error('SSE Error:', error);
eventSource.close();
};
// Function to send messages
async function sendMessage() {
const input = document.getElementById("messageText");
const message = input.value;
try {
await fetch('/messages', {
method: 'POST',
body: message
});
input.value = '';
} catch (error) {
console.error('Error sending message:', error);
}
}
</script>
</body>
</html>