Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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');
});
@wangyangkobe

This comment has been minimized.

Copy link

commented Aug 1, 2015

The output:

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

This comment has been minimized.

Copy link

commented Sep 2, 2015

Cool snippet dude! 👍

@ghost

This comment has been minimized.

Copy link

commented Sep 20, 2015

Is it actually cheap to start 5, 10, 100 internal servers? How big is the header of each instance. However, thanks for the example.

@soletan

This comment has been minimized.

Copy link

commented Sep 27, 2015

Destroying client in handler of event "data" is bad idea since "data" might be emitted multiple times while receiving several chunks of response data ... just consider downloading very large file ... you won't get just one data event on that, but destroy the connection as soon as the first chunk has arrived.

@blikenoother

This comment has been minimized.

Copy link

commented Nov 16, 2015

@soletan is there any framework for service oriented architecture which allows to call function of other connected service and registry which handles which services are up and down?

@goliatone

This comment has been minimized.

Copy link

commented Nov 20, 2015

On a nix box you can use net cat from terminal

nc 127.0.0.1 1337
@anthonygore

This comment has been minimized.

Copy link

commented Dec 21, 2015

I'm not sure you need client.destroy() on line 44. According to the docs it's only required after an error. Also, I think you should have client.end() after client.write() otherwise the server doesn't know the message is complete.

@shivasurya

This comment has been minimized.

Copy link

commented Jan 8, 2016

thank you!

@i-am-vivek

This comment has been minimized.

Copy link

commented Jan 13, 2016

Hi,
I am having problem with this code when I run it on IBM Bluemix. but locally it works fine. On server(IBM Bluemix), It throws error like,

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

Error: connect ETIMEDOUT xxx.x.xx.xx:xxxx
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)

Can you guys help me in this case?

@Mandrewdarts

This comment has been minimized.

Copy link

commented Jan 22, 2016

@i-am-vivek if I understand correctly you have to handle the 'error' event or it will kill the process.

socket.on('error', function(err) {
   console.log(err)
})

Hope this helped!

@jaggedsoft

This comment has been minimized.

Copy link

commented Feb 18, 2016

@i-am-vivek I agree with above, but if you're still having issues,it's likely due to a firewall. If you install 'ufw' it's an easy way to manage your firewall settings, you could just type ufw allow 1337 to allow connections on port 1337. Or, you could do it the iptables way:
iptables -A INPUT -p tcp -dport 1337-j ACCEPT && service iptables restart
For CentOS, you should use "firewall-cmd" command: firewall-cmd --add-port=1337/tcp --permanent

@niwsa

This comment has been minimized.

Copy link

commented May 12, 2016

@tedmiston How do I pass query parameters to a websocket endpoint?

@ORESoftware

This comment has been minimized.

Copy link

commented Oct 13, 2016

what does socket.pipe(socket) accomplish?

@fixmycode

This comment has been minimized.

Copy link

commented Oct 17, 2016

@ORESoftware it makes the socket writes whatever it reads from the client back to him, hence the "Echo server".
Socket is a stream, so basically, it connects its input to its output directly.

@Kiran-N

This comment has been minimized.

Copy link

commented Dec 9, 2016

Did any one got this error "net.Socket is not a constructor".

@BonsoirDiep

This comment has been minimized.

Copy link

commented Dec 15, 2016

@i-am-vivek
If you don't want "Echo server", let 's try:
replace:
socket.pipe(socket);
with:
```
socket.on('data', function(data){
console.log(data);
var textChunk = data.toString('utf8');
console.log(textChunk);
});

@BonsoirDiep

This comment has been minimized.

Copy link

commented Dec 15, 2016

And i try "Echo server" here:

//server:

var net = require('net');
var textChunk = '';
var server = net.createServer(function(socket) {
	socket.write('Echo server\r\n');
	socket.on('data', function(data){
		console.log(data);
		textChunk = data.toString('utf8');
		console.log(textChunk);
		socket.write(textChunk);
	});
});
server.listen(52275, '127.0.0.1');

//client:

var net = require('net');
var client = new net.Socket();
client.connect(52275, '127.0.0.1', function() {
	console.log('Connected');
	client.write('Hello, server! Love, Client.');
});
var i = 0;
client.on('data', function(data) {
	console.log('Received: ' + data);
	i++;
	if(i==2)
		client.destroy(); 
});
client.on('close', function() {
	console.log('Connection closed');
});
@WisterDesigns

This comment has been minimized.

Copy link

commented Dec 30, 2016

Can someone please give me an example of code about how to use the client in HTML file with Java Scripting?
Thanks!

@ddavis914

This comment has been minimized.

Copy link

commented Jan 17, 2017

On windows, telnet can be used as the client
'>telnet 127.0.0.0 xxxx
Where xxxx is the port number. Telnet may need to be turned on.

@wwmahww

This comment has been minimized.

Copy link

commented Feb 14, 2017

if i set the server file on a server how can i access to that . i mean if i run it on my computer i can access with ip 127.0.0.1 bot if i run it on a server site how can i do that??

@nikitakodkani

This comment has been minimized.

Copy link

commented Apr 5, 2017

How is the error handling done in the client side? Not sure how it would be done on the client side.

@gxvigo

This comment has been minimized.

Copy link

commented Apr 11, 2017

Hi There,
I am trying to use TCP client to send smtp message via telnet.
I need to send multiple commands but it seems that after the first command the connection is closed:

var client = new net.Socket();
client.connect(1025, '127.0.0.1', function() {
console.log('Connected');
client.write('HELO think.ibm');
client.write('MAIL FROM: g@think.ibm');
client.write('RCPT TO: r@think.ibm');
client.write('DATA some data.');
client.write('.');
});

console log:
Connected
Received: 220 EventMachine SMTP Server
Connection closed

What would be the best approach to send multiple commands to the same session?

Cheers.

@peter-atlanta

This comment has been minimized.

Copy link

commented Apr 14, 2017

Awesome snippet. Thanks for posting.

@marckris

This comment has been minimized.

Copy link

commented Apr 23, 2017

socket.pipe(socket) is a problem when you don't close the connection for every single request. If you want to receive multiple requests/responses on a socket, the "data" event will be called for "write" too and you will get your own data back. It seems there is no easy way to get around this.

@shaoweilee

This comment has been minimized.

Copy link

commented May 19, 2017

after running the code you showed us.
the client side:

connected
received Echo server
connection closed

without "Hello, server! Love, Client."
and after that, the server side reported an error:

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

Error: read ECONNRESET
    at exports._errnoException (util.js:907:11)
    at TCP.onread (net.js:557:26)
@suresach

This comment has been minimized.

Copy link

commented Jun 12, 2017

Can I send http request on this server?
If yes, then how do I get the url requested (in back-end)?

Eg: curl http://127.0.0.1:1337/run_code

How do I get this 'run_code' in back-end?

@thunderrun

This comment has been minimized.

Copy link

commented Jun 25, 2017

@shaoweilee
remove client.destroy(); // kill client after server's response

@Tomvictor

This comment has been minimized.

Copy link

commented Jun 27, 2017

How can I deploy the code on the server,, can I use pm2?
I have added endpoint (8010) to my Azure VM. but still not able to connect via Netcat from my local Mac.

Thanks
Tom Victor
buildfromzero.com

@abhilash007

This comment has been minimized.

Copy link

commented Jul 27, 2017

how to use express with net? please help

@agauniyal

This comment has been minimized.

Copy link

commented Aug 2, 2017

@abhilash007 why would you use express with net? net is TCP protocol while expressjs serves to http protocol.

@agauniyal

This comment has been minimized.

Copy link

commented Aug 2, 2017

@suresach by reading the HTTP headers that were sent along with request.

@ghost

This comment has been minimized.

Copy link

commented Nov 25, 2017

Thank you!

@BigDog6432

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented May 6, 2018

How can I do this in TypeScript?

@myroncama12

This comment has been minimized.

Copy link

commented May 23, 2018

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

@hosseinGanjyar

This comment has been minimized.

Copy link

commented Jun 11, 2018

Why I have error?

connect ETIMEDOUT

@MingqianYang

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Sep 13, 2018

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

This comment has been minimized.

Copy link

commented Sep 13, 2018

i need to listen on 5 5 different ports

@stochastic-thread

This comment has been minimized.

Copy link

commented Oct 9, 2018

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

This comment has been minimized.

Copy link

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.

@ajhstn

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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?

@ajhstn

This comment has been minimized.

Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.