I am using websocket in conjuction with an http server for a Node.js SPA. My use of websocket is to read an index file from the server and push it to the client. The websocket is working except when I refresh the page.
Can someone assist me in reconnecting the websocket?
I am listening for an onClose
event and calling the method that creates the websocket. The error I get once I refresh the page is:
Socket encountered error: write after end Closing socket
/home/pi/data_collector_access_point/node_modules/ws/lib/websocket.js:829
websocket.readyState = WebSocket.CLOSING;
^
TypeError: Cannot set property 'readyState' of undefined
at Socket.socketOnClose (/home/pi/data_collector_access_point/node_modules/ws/lib/websocket.js:829:24)
at emitOne (events.js:121:20)
at Socket.emit (events.js:211:7)
at TCP._handle.close [as _onclose] (net.js:567:12)
Server.js
serverWS(address){
let server = address
const WebSocket = require('ws');
let wss = new WebSocket.Server({ server });
var socketstate = 1;
wss.on('connection', function connection(ws, req) {
ws.on('message', function incoming(message) {
});
ws.onclose = function(){
socketstate = 0
console.log('ws.onclose()')
setTimeout(function(){
console.log('reconnct ', server)
let fti_server = new create_server()
fti_server.serverWS(server)
},3000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
function sendme(data){
switch(socketstate){
case 0:
console.log('sendme() socket state', socketstate)
break;
case 1:
console.log('sendme() socket state', socketstate)
if(ws.readyState == 1){
updater((data)=>{
ws.send(data)
})
}
break;
}
}
function reOpen(){
console.log('reopen', wss)
wss = new WebSocket.Server({ server });
}
setInterval(()=>{
switch(ws.readyState){
case 1 :
console.log('switch case ws state on')
sendme(data)
break;
case 2 :
console.log('ws state 2')
break
case 3 :
console.log('switch case ws state not on')
break;
}
},1000);
})
}
I am listening to the websocketReadystate to see if the websocket is open, closed, closing etc. Once opened I would continue sending the index data.
I am referencing this reconnection situation .