简体   繁体   中英

Handling an error on a tcp connection using the “net” module of NodeJS

Im trying to learn the "net" module of NodeJS, but i have run into an annoying problem. My code is in 2 scripts.

//index.js
var net = require("net")

var server = net.createServer(socket=>{
    socket.write("Hello!")
})
server.on("error", err=>{
    console.error(err)
})
server.listen(50001)

and

//client
var net = require("net")

net.createConnection({
    host:"localhost",
    port: 50001
})
.on("data", data=>{
    console.log(data.toString())
})

when i run the 2 scripts...

node index.js
node client.js

...the message "Hello." is sent to the client with no problems, If i CTRL+C out of the client (to simulate an unexpected closure), i get the following error

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

Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)

which i find strange, as I have registered an "error" event on the server. What am i doing wrong?

The program registers a handler for an 'error' event on the server's listening socket, but it does not register an 'error' handler on the separate new socket that is created to carry the connection that is made by the client. (Every connection to the server gets a separate new socket, distinct from the listening socket and from any other connections that have been made earlier.)

That new connection socket is the one that is passed as the argument to the server's connect handler. It's the socket that you write 'Hello.' into.

If you want the program to be notified of an error on that new socket then you must register an 'error' handler on the new socket. Something like this:

var net = require("net")

var server = net.createServer(socket=>{
    socket.on('error', err=>{
        console.error('connected socket: ' + err);
    });
    socket.write("Hello!")
})
server.on("error", err=>{
    console.error(err)
})
server.listen(50001)

Similarly, if you wanted the server to read data from the connection then you would register a handler for the 'data' event on the new connection socket, in the same way as you already did on the client's socket.

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