ksatione
ksatione

Reputation: 3

'Error: connect ECONNREFUSED' when connecting to web socket server?

I have this OSC server that receives and sends messages to other clients, one of them being a web socket server that controls a timer.

Here is the script to it:

const osc = require('osc');
const WebSocket = require('ws');

let ws = undefined;

// web socket, timer
function webSocket() {
    ws = new WebSocket('ws:192.168.1.118:4000');

    ws.on('open', function open() {
        console.log('WebSocket connected');
    });

    ws.on('close', function close() {
        console.log('WebSocket disconnected, attempting to reconnect...');
        setTimeout(webSocket, 1000);
    });

    ws.on('error', function error(err) {
        console.error('WebSocket encountered an error: ', err.message, 'Closing socket');
        ws.close();
    });
}

webSocket();

var udp = new osc.UDPPort({
    localAddress: "0.0.0.0",
    localPort: 8000, 
});

udp.on('ready', function () {
    console.log('OSC Server is listening');
    console.log(JSON.stringify(udp));
});

// Receive osc message
udp.on('message', function (msg, timeTage, info) {
    console.log('An OSC message received: ', msg);

    // Send exact message to movie player program
    if(info.address !== '10.4.0.95') {
        udp.send(msg, '10.4.0.95', 9004);
    }

    // Send message to tablet
    if (msg.address.startsWith('/mov/moviePlayhead') && info.address !== '10.4.0.94') {
    udp.send(msg, '10.4.0.94', 9003)
    }

    // Send message to web socket, timer
    if (msg.address === '/bank/1/trig/3') {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({event:'kaleidoscope', action: 'play', type: '3'}));
        }
    }
    else if (msg.address === '/bank/1/trig/2') {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({event:'kaleidoscope', action: 'play', type: '5'}));
        }
    }
    else if (msg.address === '/bank/1/trig/1') {
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify({event:'kaleidoscope', action: 'play', type: '7'}));
        }
    }

});

udp.open();

It runs fine for the most part, but sometimes this error comes up:

Error: connect ECONNREFUSED 192.168.1.118:4000 at TCPConnectWrap.afterConnect [as oncomplete] {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '192.168.1.118',
  port 4000
}

It seems as if it's randomly happening. The server at 192.168.1.118:4000 is running and the timer client is connected to it. The only way to fix it is if I restart the OSC server, but I don't want to have to do that every time.

What is the issue? And how can I prevent it from happening or reconnect properly when it does. I have reconnect logic in the code, but it didn't seem to help.

Upvotes: 0

Views: 171

Answers (0)

Related Questions