aspnetcore/samples/SocketsSample/wwwroot/polling.html

77 lines
2.6 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
document.addEventListener('DOMContentLoaded', () => {
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 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 poll(connectionId, xhr) {
var url = `/chat/poll?id=${connectionId}`;
xhr.open("POST", url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
var child = document.createElement('li');
child.innerText = xhr.response;
document.getElementById('messages').appendChild(child);
poll(connectionId, xhr);
}
}
xhr.send(null);
}
xhr('GET', '/chat/getid').then(connectionId => {
document.getElementById('sendmessage').addEventListener('click', () => {
let data = document.getElementById('data').value;
send(connectionId, data);
});
poll(connectionId, new XMLHttpRequest());
});
});
</script>
</head>
<body>
<h1>Long Polling</h1>
<input type="text" id="data" />
<input type="button" id="sendmessage" value="Send" />
<ul id="messages"></ul>
</body>
</html>