Skip to content

Instantly share code, notes, and snippets.

@tedmiston
Last active February 19, 2024 21:55
Show Gist options
  • Save tedmiston/5935757 to your computer and use it in GitHub Desktop.
Save tedmiston/5935757 to your computer and use it in GitHub Desktop.
Node.js TCP client and server example
/*
In the node.js intro tutorial (http://nodejs.org/), they show a basic tcp
server, but for some reason omit a client connecting to it. I added an
example at the bottom.
Save the following server in example.js:
*/
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
/*
And connect with a tcp client from the command line using netcat, the *nix
utility for reading and writing across tcp/udp network connections. I've only
used it for debugging myself.
$ netcat 127.0.0.1 1337
You should see:
> Echo server
*/
/* Or use this example tcp client written in node.js. (Originated with
example code from
http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html.) */
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
@BigDog6432
Copy link

BigDog6432 commented Dec 20, 2017

So I took this example and modified it slightly such that the client writes data to the server. This should be doable since the client socket does support a write. In one of my use cases the client sends a fair amount of data to server in which case I get an ECONNRESET error. Attached are client1 and server1 snippets. I was wondering if anyone has seen this and if they know what is going wrong under the covers.

Thanks in advance
BigDog6432


Client1:

var net = require('net');
var client = new net.Socket({writeable: true}); //writeable true does not appear to help

client.on('close', function() {
console.log('Connection closed');
});
client.on('error', function(err) {
console.error('Connection error: ' + err);
console.error(new Error().stack);
});

client.connect(52275, '127.0.0.1', function() {
var count = 0;
console.log('Connected');
for(var i = 0; i < 100000; i++) {
client.write('' + i + '');
//bufferSize does not seem to be an issue
//console.info(client.bufferSize);
}
});


Server1:
var net = require('net');
var count = 0;

var server = net.createServer(function(socket) {

socket.pipe(socket);  //With this uncommented I get an ECONNRESET exception after 14299 writes with it commented it 

hangs after 41020 writes

socket.on('data', function(data) {

    console.info(count++);  //This makes it occur sooner
	//count++;

	//maxConnections is not the issue
	//server.getConnections(function(err, count) {
		
		//console.info('count = ' + count);
	//});
});

socket.on('close', function() {
    console.info('Socket close');
});

socket.on('error', function(err) {
    console.error('Socket error: ' + err + ', count = ' + count);
	console.error(new Error().stack);
});

});

server.listen(52275, '127.0.0.1');

I think I solved my own issue. I believe the issue had to do with not all of the event listeners close, data, drain, end, lookup, timeout were implemented. I have been playing around and did not expect that the client would receive back a data or drain event to be called which in turn I believe resulted in the error.

@manuGallegos
Copy link

manuGallegos commented Apr 26, 2018

Hi everyone!

i'm connecting to a telnet server:

`var net = require('net');

var client = new net.Socket();
client.connect(23, '192.168.1.180', function() {
console.log('Connected');
});

client.on('error', function(err) {
console.error('Connection error: ' + err);
console.error(new Error().stack);
});

client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy();
});

client.on('close', function() {
console.log('Connection closed');
});
but theconsole.log('Received: ' + data);is: ??%??☺??♥??'??▼?? ?? I was waiting for a login message or something like that. then i try to use.toString('utf8')on data. but is the same log. when i usetypeof(data);` and the result is a object.

please help!!!!!!.
I'm sure the connection to my telnet server is correct

@ItsGravix
Copy link

How can I do this in TypeScript?

@myroncama12
Copy link

Coool. I have my server on C and this connects perfectly with the server. Thanks :D

@hosseinGanjyar
Copy link

Why I have error?

connect ETIMEDOUT

@MingqianYang
Copy link

MingqianYang commented Jul 22, 2018

when I run client, it shows on server terminal:

screen shot 2018-07-22 at 2 08 01 pm

And my client terminal is:
screen shot 2018-07-22 at 2 17 07 pm

I don't know what happed. I suppose it could be firewall problems, but I am not sure.
Can someone help me?

@PRAMANJ
Copy link

PRAMANJ commented Aug 5, 2018

Hi
In your code, you are closing the client after getting response from TCP server. What if I want to get a response in a loop continuously? I tried using promises with the following code: (My TCP client is in NodeJS and TCP server is external JAVA application, which waits for request from client and sends the response to client).

function getData(cmd){ return new Promise(function(resolve, reject){ client.on('data', function (data){ console.log("!!!!!! promise called"); resolve(data); }); client.on('error',function (error){ reject(error); }); client.write(cmd); }) .catch(function (error) { // oops, error console.log(error.message); }); }
Where client is a global variable representing TCP socket client initialized once in the beginning to IP address and port number. I call this function in a a loop something like this:

Timer loop{
    getData("RET").then(.....act on data....).catch(...flag errors ...)
}``

It works fine , but every time server returns one extra "console.log("!!!!!! promise called");" line. Once in first cycle, twice in second, thrice in third and so on... It keeps adding an client.on listener and crosses the limit of linterers in nodeJS. What is wrong in the above code? How to rectify it?

@amoopoori
Copy link

hi
is it a server.listen(1337, '127.0.0.1'); command change to another port?
i try it and it work only on 1337

@amoopoori
Copy link

i need to listen on 5 5 different ports

@stochastic-thread
Copy link

you could probably set up some kind of nginx proxy_pass redirection scheme that forwards all incoming http requests that come in on a given set of specific ports to a single port that your web server socket has bound to

I've done this for a single port to port redirection (in my use case it was coupled with https termination but that is irrelevent to your situation.)

in principle I don't see why that wouldn't work. or just run 5 web servers but thats misguided if they are just doing the same work, depending on what your scaling needs are.

@klys
Copy link

klys commented Nov 10, 2018

client.write do not really send data to the server, it just writes over the same socket of the client.

---edit----

Ok, I just figured it out the server is an ECHO server, which means, it sends what it received.

so client.write send information to the server and the server response it, the problem I was having is: the event server.on('data') was not being triggered, that is because server.on('data') do not hold the SOCKET of the server, it held in the moment of the initialization of the server in net.CreateServer callback function.

That is it.

@adrwh
Copy link

adrwh commented Feb 17, 2019

Hello, i want to use this to create a 3 way chat service on the command line. I created the server using your code, and connected to it from two terminal windows using the ncat, however the server only echo's each clients request back to that particular client. I want to echo back to each client, so that it feels like a group chat?

screen shot 2019-02-18 at 7 02 21 am

@whhb
Copy link

whhb commented Feb 18, 2019

This is really fun, I have been playing with this today and you have definitely distracted me. Ignore my previous issue, I have progressed and now have a basic “chat room” with multiple clients.. I have been using ncat as the client, but I need more logic so I’m trying to implement your node client. So far it works, connects to the server and writes the initial text..

But all subsequent message don’t seem to go back to the server?

Apart from the very first client.write how do I send a mother client.write after the user hits enter?

@adrwh
Copy link

adrwh commented Feb 18, 2019

This is really fun, I have been playing with this today and you have definitely distracted me. Ignore my previous issue, I have progressed and now have a basic “chat room” with multiple clients.. I have been using ncat as the client, but I need more logic so I’m trying to implement your node client. So far it works, connects to the server and writes the initial text..

But all subsequent message don’t seem to go back to the server?

Apart from the very first client.write how do I send a mother client.write after the user hits enter?

@rajnisheu
Copy link

newbies who visit this many years later may find this video on youtube helpful to get started with the server side https://www.youtube.com/watch?v=HyGtI17qAjM

@YodaEmbedding
Copy link

YodaEmbedding commented Nov 29, 2019

Is Hello, server! Love, Client. guaranteed to print? It seems like there's a race condition.

Actually, is anything other than E guaranteed to print?

@masvarn
Copy link

masvarn commented Feb 19, 2020

Hi, is it possible to use this to connect to a network share (smb1)?

Copy link

ghost commented Sep 29, 2020

The output:

Connected
Received: Echo server
Hello, server! Love, Client.
Connection closed

all is fine

@hamid814
Copy link

this gist was really helpful for me, thank you dude

@henrydcs
Copy link

Hi guys and gals,
I'm trying to create a simulator using Javascript for the front end which I can do, but I'm having a hard time with Node.js for the backend. When I click on, say, a Cisco router icon, I want the a physical connection to occur between my PC and the physcial router that is connected via ethernet. It is a laboratory router (no internet connection). I was thinking that I should download the NPM package telnet-client and require it in the node.js file. I don't know what to do from there. I assume I have to require net as well. Will someone help me. Please... Pretty please :)

@terthesz
Copy link

terthesz commented Apr 5, 2021

Please use arrow functions!

Copy link

ghost commented Jul 15, 2021

hello, how can you prevent DDOS attacks on this code?

@ABHINAVABHISHEK
Copy link

how to set tcp headers on request and receive in the server

@zakcodez
Copy link

how to set tcp headers on request and receive in the server

I don't think you can set headers with TCP. HTTP maybe what you are looking for

@Raghupathy-max
Copy link

'Received: ' + data

I also have a same issue.......

@lenn-mark
Copy link

require("net") is not working in 16.13.1
when i move to 18.x now it says digital envelope routines unsupported
.......

@seyyednaquib
Copy link

you try to connect to another pc port? if yes, make sure to allow inbound firewall

@k-zehnder
Copy link

this gist was really helpful for me, thank you dude

same! thank you!

@manniecobham
Copy link

I have multiple simultaneous connections. how can I write to a particular client if the remotePort and remoteAddress is stored to the DB. the new Socket() command does not work in my case because it creates a new instance of this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment