1
0
mirror of https://github.com/morris/vanilla-todo.git synced 2025-01-17 12:48:15 +01:00

warn when dev server disconnects

This commit is contained in:
Morris Brodersen 2023-11-24 16:39:28 +01:00
parent 89f6a0f390
commit f3c753b645
2 changed files with 14 additions and 9 deletions

View File

@ -1,3 +1,4 @@
/* eslint-disable no-console */
const socket = new WebSocket(
`${(location.protocol === 'http:' ? 'ws://' : 'wss://') + location.host}/`,
);
@ -28,3 +29,7 @@ socket.addEventListener('message', (message) => {
// otherwise, reload page
if (reload) location.reload();
});
socket.addEventListener('close', () => {
console.warn('Development server disconnected');
});

View File

@ -125,20 +125,20 @@ server.listen(port);
// WebSocket server
const wsClients = new Set();
const wsServer = new WebSocketServer({ server });
const webSocketServer = new WebSocketServer({ server });
const webSockets = new Set();
wsServer.on('connection', (client) => {
wsClients.add(client);
webSocketServer.on('connection', (client) => {
webSockets.add(client);
});
function broadcast(message) {
for (const wsClient of wsClients) {
if (wsClient.readyState === WebSocket.OPEN) {
wsClient.send(JSON.stringify(message));
for (const webSocket of webSockets) {
if (webSocket.readyState === WebSocket.OPEN) {
webSocket.send(JSON.stringify(message));
} else {
wsClients.delete(wsClient);
wsClient.terminate();
webSockets.delete(webSocket);
webSocket.terminate();
}
}
}