JSFiddle - React, Tailwind, and code Playground
by tonyleeper
HTML
<div class="connection-state"></div>
<div class="time"></div>
CSS
.connection-state {
height: 20px;
background-color: #990000;
}
.connection-state.connected {
background-color: #009900;
}
JavaScript
var socket;
function connect() {
try {
socket = new WebSocket('ws://localhost:8080');
socket.onerror = function () { }
socket.onmessage = function (event) {
document.querySelector('.time').innerHTML = event.data;
}
socket.onopen = function () {
socket.connected = true;
document.querySelector('.connection-state').classList.add('connected');
socket.send('hello from the browser!');
}
socket.onclose = function () {
socket.connected = false;
document.querySelector('.connection-state').classList.remove('connected');
}
} catch (e) {}
}
connect();
setInterval(function () {
if (!socket || !socket.connected) {
connect();
}
}, 1000);