aspnetcore/samples/SocketsSample/wwwroot/polling.html

110 lines
3.4 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
});
};
});
}
function poll(xhr) {
var url = `${sock.url}/poll?id=${sock.connectionId}`;
xhr.open('POST', url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
sock.onmessage({ data: xhr.responseText });
poll(xhr);
}
}
xhr.send(null);
}
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) {
// Do something useful here
}
}
xhr.send(data);
};
xhr('GET', `${sock.url}/getid`).then(connectionId => {
sock.connectionId = connectionId;
sock.onopen();
poll(new XMLHttpRequest());
});
}
document.addEventListener('DOMContentLoaded', () => {
var url = location.hash || '#/chat';
var sock = new socket(url.substring(1));
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>Long Polling</h1>
<form id="sendmessage">
<input type="text" id="data" />
<input type="submit" value="Send" />
</form>
<ul id="messages"></ul>
</body>
</html>