question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Handling of ECONNREFUSED

See original GitHub issue

Hi,

I’d like to start a connection before the server is up and keep retrying until the connection is finally accepted. I’m using ‘ws’ in node.js as the underlying ws implementation. The problem with this is the ‘close’ event comes before ‘open’ (actually no ‘open’ comes, only a ‘close’ and an ‘error’), so the timeout handler is not removed and I get the following error during the second try:

RWS: init
RWS: connect
RWS: bypass properties
error:  { Error: connect ECONNREFUSED 127.0.0.1:8167
    at Object.exports._errnoException (util.js:1024:11)
    at exports._exceptionWithHostPort (util.js:1047:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1150:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8167 }
RWS: handleClose { shouldRetry: true }
RWS: retries count: 1
RWS: handleClose - reconnectDelay: 2940.596362061423
Connection closed:  1006
RWS: connect
RWS: bypass properties
RWS: timeout
events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: closed before the connection is established
    at WebSocket.close (<project>\node_modules\ws\lib\WebSocket.js:270:28)
    at Timeout._onTimeout (<project>\node_modules\reconnecting-websocket\dist\index.js:126:16)
    at ontimeout (timers.js:469:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5)

Extract from my code:

const ReconnectingWebSocket = require('reconnecting-websocket');
const WebSocket = require('ws');
this.ws = new ReconnectingWebSocket(url, [], {constructor: WebSocket, debug: true});

this.ws.on('error', (data) => {
   console.log('error: ', data);
});

this.ws.on('close', (code, reason) => {
   console.log('Connection closed: ', code, reason);
   this.connectionStatus = 'disconnected';
});

Is there any workaround for this? Is this an issue with reconnecting-websocket or ws?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
aysuiocommented, Jul 22, 2022

@aysuio I stopped using this library and started using https://github.com/websockets/ws with my own implementation of reconnection.

websocketService.js

const WebSocket = require('ws')

function connect() {
  console.log('Connecting...')
  let ws = new WebSocket('ws://localhost:3333')

  ws.on('open', () => {
    console.log('Connection open')
  })

  ws.on('message', data => {
    console.log(data.toString('utf-8'))
  })

  ws.on('close', () => {
    console.log('Connection close')
    ws = null
    setTimeout(connect, 1000)
  })

  ws.on('error', err => {
    console.log('Connection error')
    console.error(err)
  })
}

connect()

ws version: ^8.8.1

To see it working, try to stop your ws server or add handshakeTimeout: 1 option to the 2nd parameter of WebSocket instance.

...
let ws = new WebSocket('ws://localhost:3333', { handshakeTimeout: 1 })
...

It should now reconnect after the timeout and when the network is down.

I also used that library instead of this one, which just costed me around 1 hour to implement the reconnection feature. Should have done this long time ago, XD.

Thanks for the reply

1reaction
Szellemcommented, Oct 23, 2017

As mentioned in the linked issue, the event handlers of old ws instance are set to undefined after the connection error, so the following line removes all of them from the new instance too: https://github.com/pladaria/reconnecting-websocket/blob/31a0f01af4c96dfb1ba0c17b1124de204cd0e513/dist/index.js#L45

After commenting this block out and using addEventListener() instead of on in my code, it works with ws lib. A possible fix would be to skip assignment of undefined listeners in this block. What do you think?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Step-by-Step Fix "ECONNREFUSED - Connection refused by ...
In this guide we show you how to resolve FileZilla's ECONNREFUSED - Connection refused by server error along with tips and tools that...
Read more >
Catching ECONNREFUSED in node.js with http.request?
I'm handling on error event for both to make sure my app does not crashes. – Aebsubis. Jul 29, 2014 at 16:18. Add...
Read more >
ECONNREFUSED - Connection refused by the server
This error indicates that the user is trying to connect to your server and is unable to connect to the port. There are...
Read more >
Is "ECONNREFUSED, Connection refused" uncatchable?
First, if you don't handle error events they throw. Second, http requests basically never emit error events only client emits errors because it's...
Read more >
15 Common Error Codes in Node.js and How to Fix Them
The ECONNREFUSED error is produced when a request is made to an endpoint but a connection could not be established because the specified ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found