1
0
This repository has been archived on 2024-10-30. You can view files and clone it, but cannot push or open issues or pull requests.
SDI-WebSocket-Exercise/tempbat.js
2024-04-11 19:19:01 +02:00

53 lines
1.6 KiB
JavaScript

$(document).ready(function() {
var socket;
var logElement = document.getElementById('log');
var tempButton = document.getElementById('temp');
var batButton = document.getElementById('bat');
var disconButton = document.getElementById('discon');
function logMessage(message) {
logElement.value += message + '\n';
}
function connect() {
socket = new WebSocket("ws://webex.sdi.hevs.ch/temp");
socket.onopen = function() {
logMessage('Connection open');
tempButton.removeAttribute('disabled');
batButton.removeAttribute('disabled');
disconButton.textContent = 'Disconnect';
};
socket.onclose = function() {
logMessage('Connection close');
tempButton.setAttribute('disabled', 'true');
batButton.setAttribute('disabled', 'true');
disconButton.textContent = 'Reconnect';
};
socket.onerror = function(error) {
logMessage('Error: ' + error.message);
};
socket.onmessage = function(msg) {
logMessage(msg.data);
};
}
connect();
document.getElementById('temp').addEventListener('click', function() {
socket.send("temp");
});
document.getElementById('bat').addEventListener('click', function() {
socket.send("bat");
});
document.getElementById('discon').addEventListener('click', function() {
if (socket.readyState === WebSocket.OPEN) {
socket.close();
} else {
connect();
}
});
});