1

in the example NodeJS server (at end) why does (it seems) socket.end() on a netcat connection cause a ECONNRESET server error?

Observe, a socket-object error on server with client:

TERMINAL 1
netcat localhost 9000
Hello.
Goodbye.

TERMINAL 2
==> A Connection connected
==> The Server is disconnecting a connection
{ [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }

Now observe, no socket-object error on server with client:

TERMINAL 1
telnet localhost 9000
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Hello.
Goodbye.
Connection closed by foreign host.

TERMINAL 2
==> A Connection connected
==> The Server is disconnecting a connection
==> A Connection disconnected

I'm looking for an answer that will fix the error, or failing that, very clearly explain why this must happen.

Many thanks,
Jason

import TCP from "net"
import Promise from "Bluebird"

const log = console.log



const server = TCP.createServer((conn) => {

  conn.setEncoding('utf8')

  log("==> A Connection connected")

  conn.write("Hello.\n", async function () {
    await Promise.delay(3000)
    if (!conn.destroyed) {
      log("==> The Server is disconnecting a connection")
      conn.end("Goodbye.\n")
    }
  })

  conn.on("error", log)

  conn.on("end", () => {
    log("==> A Connection disconnected")
  })

  conn.on("data", (message) => {
    log("==> A Connection says:\n%s", message)
  })
})



const port = 9000

server.listen(port, () => {
  log(`==> The Server is listening on port ${port}`)
})
2
  • Thanks for your link. If you want to get answers - include your code here Commented Sep 8, 2016 at 19:35
  • @baao Ok I've copied over the code, thanks. Commented Sep 8, 2016 at 19:40

1 Answer 1

1

The reason for this has something to do with how some versions (not all) of netcat handle the closing of TCP connections.

The exact cause goes beyond my knowledge of TCP, so I can't help you with that (all I can say is that ECONNRESET means that Node tried to read from a connection that was reset/closed already by netcat).

A solution that works for me is to call destroy() on the socket once the last message was sent:

conn.end("Goodbye.\n")
conn.destroy()

I guess it presents Node from performing any more reads on the socket, which could cause the error.

Sign up to request clarification or add additional context in comments.

1 Comment

I'll wait to accept a more detailed answer but this is a helpful start, so thank-you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.