简体   繁体   中英

Why doesn't Node.js throw an error when it can't connect to socket?

When i call both of these functions only the upper one fails and returns an error

const { Socket } = require("net")

class Client {
  connect () {
    this.a = new Socket()  
    this.a.connect(this.port, this.host)
    
    this.socket = new Socket()  
    this.socket.connect(this.port, this.host)
  }
}

The problem is, that i know that the port this should connect to, is not used. Both functions should throw an error. If i call the lower one first, still the one with this.a fails.

If i use this.socket for both, the first one always fails even if i change the order of them.

To differentiate between them i used a different port to connect to but also unused.

this.socket = new Socket()
this.socket.connect(6743, this.host)

this.a = new Socket()
this.a.connect(6744, this.host)

The this.port and this.host variables are not the problem, because if run the script while the server on the port is online it works.

Error Message that should be thrown:

events.js:291
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:6744
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 6744
}```

Like other users have mentioned, the second error is not being triggered because the application effectively stops running after the first error. To prove this, you could try putting a console.log between your two attempts to connect to a socket and see that won't run as expected either.

In nodeJs some module throw error in event

Socket throw error in event.on('error') and you should checked event

I hope below link help you:

https://stackoverflow.com/a/25847067/6759368

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM