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/chat.js

48 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2024-04-11 17:19:01 +00:00
$(document).ready(function() {
var socket;
var logElement = document.getElementById('chatlog');
var sendButton = document.getElementById('sendButton');
var closeButton = document.getElementById('closeButton');
function logMessage(message) {
logElement.value += message + '\n';
}
function connect() {
socket = new WebSocket("ws://webex.sdi.hevs.ch/chat");
socket.onopen = function() {
logMessage("Connected.");
sendButton.removeAttribute("disabled");
closeButton.textContent = "End";
};
socket.onmessage = function(msg) {
logMessage(msg.data);
};
socket.onclose = function() {
logMessage("Disconnected.");
sendButton.setAttribute("disabled", "true");
closeButton.textContent = "Reconnect";
};
socket.onerror = function() {
logMessage("Error.");
};
}
connect();
document.getElementById("sendButton").onclick = function() {
var msg = document.getElementById("msg").value;
socket.send(msg);
document.getElementById("msg").value = "";
};
document.getElementById("closeButton").onclick = function() {
if (socket.readyState === WebSocket.OPEN) {
socket.close();
} else {
connect();
}
};
});