64 lines
1.8 KiB
JavaScript
64 lines
1.8 KiB
JavaScript
jQuery(document).ready(function($){
|
|
let ws = null;
|
|
|
|
$('#reconnectButton').click(function(ev){
|
|
ev.preventDefault();
|
|
|
|
if (ws) {
|
|
$('#reconnectButton').text('Connect');
|
|
ws.close();
|
|
ws = null;
|
|
} else {
|
|
$('#reconnectButton').text('Disconnect');
|
|
setWsStatus('Connecting');
|
|
ws = new WebSocket(window.location.href.replace(/^http/, "ws"));
|
|
ws.onopen = function(event) {
|
|
setWsStatus('Connected');
|
|
$('#sendForm input').focus();
|
|
}
|
|
ws.onclose = function(event) {
|
|
setWsStatus('Closed');
|
|
$('#reconnectButton').text('Connect');
|
|
ws.close();
|
|
ws = null;
|
|
}
|
|
ws.onerror = function(event) {
|
|
setWsStatus('Error');
|
|
}
|
|
ws.onmessage = function(event) {
|
|
if (typeof event.data == 'string') {
|
|
pushLine('Received ' + event.data);
|
|
} else if (typeof event.data == 'object') {
|
|
pushLine('Received binary message!');
|
|
} else {
|
|
pushLine('Unknown msg data type ' + typeof event.data);
|
|
}
|
|
};
|
|
}
|
|
}).click();
|
|
|
|
$('#sendForm').submit(function(ev){
|
|
ev.preventDefault();
|
|
|
|
if (!ws) {
|
|
alert('please connect first');
|
|
return;
|
|
}
|
|
|
|
const input = $('#sendForm input');
|
|
const val = input.val();
|
|
pushLine('Sending ' + val);
|
|
ws.send(val);
|
|
input.val('').focus();
|
|
});
|
|
});
|
|
|
|
function pushLine(line) {
|
|
$('#logView').append($('<p>').text(new Date().toLocaleTimeString() + ': ' + line));
|
|
}
|
|
|
|
function setWsStatus(status) {
|
|
$('#wsStatus').text(status);
|
|
pushLine('Status changed to ' + status);
|
|
}
|