I have a simple Express.js app which starts a websocket server and then the front-end connects to this server. When I start both the back-end Express.js server and the front-end server, everything works fine and I can see the incoming messages from the back-end being logged in the front-end each second.
However, when I refresh my browser, the Express.js server crashes and logs this:
Error: WebSocket is not open: readyState 3 (CLOSED)
The Express.js code looks like this:
import * as WebSocket from 'ws';
const wss = new WebSocket.Server({ server });
const connect = function () {
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
ws.send(createMessage());
setInterval(() => {
ws.send(generateMsg());
}, 1000);
ws.on('error', (err) => {
console.warn(`Client disconnected - reason: ${err}`);
setTimeout(() => {
connect();
}, 1000)
})
});
}
connect();
And in my front-end, I have this:
private subject = webSocket("ws://localhost:8999");
connect() {
this.subject.subscribe(
(msg) => {
console.log(msg);
},
err => {
setTimeout(() => {
this.connect();
}, 1000)
},
() => console.log('complete')
);
}
connect();
Any ideas why the reconnection between the front-end and the back-end doesn’t work?