blinkdog/telnet-stream

How to close a connection?

codemeasandwich opened this issue ยท 2 comments

Thank you for this lib.

I want to use it in a project but how do I close the connection.
In your example your exit the process but I cant do that on the live server.

How can I gracefully close a connection?

Thanks

I'm glad the lib was useful!

Gracefully closing a connection is a call to end(). Which object needs to receive the call to end() depends on the way that you're using the library.

If you are wrapping a net.Socket in a TelnetSocket, then a call to end() will do that. You can call it on either the raw Socket being wrapped or the TelnetSocket wrapper (which will pass the call to the raw Socket).

If you are wrapping streams with the TelnetInput and TelnetOutput transform streams, then end() should be called on the underlying raw output stream.

Here's a little example of a server that listens for new connections, tells them the current date/time, and then gracefully closes their connection. Note that the clients are disconnected, but the server keeps going. It continues to listen for new client connections until it is killed.

  // get references to the required things
  var TelnetSocket, handleNewConnection, net, server;

  net = require("net");

  ({TelnetSocket} = require("telnet-stream"));

  // define a handler function for new incoming connections
  handleNewConnection = function(socket) {
    var tSocket;
    // wrap the raw socket in our TelnetSocket
    tSocket = new TelnetSocket(socket);
    // write the date to the connection
    tSocket.write(`${new Date().toString() + "\n"}`);
    // close the connection
    return tSocket.end();
  };

  // create a server and attach handleNewConnection as our handler
  // for 'connection' events
  server = net.createServer(handleNewConnection);

  // start the server listening, on port 3000
  server.listen(3000);

To connect to this server, just use this command: telnet 127.0.0.1 3000

This is the output that I get in my shell:

blinkdog@titan ~ $ telnet 127.0.0.1 3000
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Mon Mar 19 2018 18:51:22 GMT-0500 (CDT)
Connection closed by foreign host.

Please let me know if there is anything unclear?

Thank you for the help ๐Ÿ˜