aspnetcore/samples/SocketsSample/wwwroot/sse.html

108 lines
3.2 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
function socket(url) {
var sock = this;
sock.url = url;
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
});
};
});
}
sock.onopen = function () { };
sock.onmessage = function () { };
sock.onerror = function (event) { };
sock.send = function (data) {
if (!sock.connectionId) {
throw "Not connected";
}
var xhr = new XMLHttpRequest();
var url = `${sock.url}/send?id=${sock.connectionId}`;
xhr.open('POST', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
}
}
xhr.send(data);
};
// Start the connection
xhr('GET', `${sock.url}/getid`).then(connectionId => {
sock.connectionId = connectionId;
let source = new EventSource(`${sock.url}/sse?id=${connectionId}`);
source.onopen = function () {
sock.onopen();
};
source.onerror = function (err) {
sock.onerror(err);
};
source.onmessage = function (data) {
sock.onmessage(data);
};
});
};
document.addEventListener('DOMContentLoaded', () => {
var sock = new socket('/chat');
sock.onopen = function () {
console.log('Opened!');
};
sock.onmessage = function (event) {
var child = document.createElement('li');
child.innerText = event.data;
document.getElementById('messages').appendChild(child);
};
document.getElementById('sendmessage').addEventListener('submit', event => {
let data = document.getElementById('data').value;
sock.send(data);
event.preventDefault();
});
});
</script>
</head>
<body>
<h1>Server Sent Events</h1>
<form id="sendmessage">
<input type="text" id="data" />
<input type="submit" value="Send" />
</form>
<ul id="messages"></ul>
</body>
</html>