79 lines
2.5 KiB
HTML
79 lines
2.5 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta charset="utf-8" />
|
|
<title></title>
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
function send(connectionId, data) {
|
|
var xhr = new XMLHttpRequest();
|
|
var url = `/chat/send?id=${connectionId}`;
|
|
xhr.open("POST", url, true);
|
|
xhr.onreadystatechange = function () {
|
|
if (xhr.readyState == 4 && xhr.status == 200) {
|
|
}
|
|
}
|
|
xhr.send(data);
|
|
}
|
|
|
|
function xhr(method, url) {
|
|
return new Promise((resolve, reject) => {
|
|
let xhr = new XMLHttpRequest();
|
|
xhr.open(method, url, true);
|
|
xhr.send();
|
|
xhr.onload = () => {
|
|
if (xhr.status >= 200 && xhr.status < 300) {
|
|
resolve(xhr.response);
|
|
} else {
|
|
reject({
|
|
status: xhr.status,
|
|
statusText: xhr.statusText
|
|
});
|
|
}
|
|
};
|
|
|
|
xhr.onerror = () => {
|
|
reject({
|
|
status: xhr.status,
|
|
statusText: xhr.statusText
|
|
});
|
|
};
|
|
});
|
|
}
|
|
|
|
xhr('GET', '/chat/getid').then(connectionId => {
|
|
let source = new EventSource(`/chat/sse?id=${connectionId}`);
|
|
|
|
source.onopen = function () {
|
|
console.log('Opened!');
|
|
};
|
|
|
|
source.onerror = function (err) {
|
|
console.log('Error: ' + err.type);
|
|
};
|
|
|
|
source.onmessage = function (data) {
|
|
var child = document.createElement('li');
|
|
child.innerText = data.data;
|
|
document.getElementById('messages').appendChild(child);
|
|
};
|
|
|
|
document.getElementById('sendmessage').addEventListener('click', () => {
|
|
let data = document.getElementById('data').value;
|
|
send(connectionId, data);
|
|
});
|
|
});
|
|
});
|
|
|
|
</script>
|
|
</head>
|
|
<body>
|
|
<h1>Server Sent Events</h1>
|
|
<input type="text" id="data" />
|
|
<input type="button" id="sendmessage" value="Send" />
|
|
|
|
<ul id="messages">
|
|
|
|
</ul>
|
|
</body>
|
|
</html> |