Last active
October 9, 2024 11:32
-
-
Save tedmiston/5935757 to your computer and use it in GitHub Desktop.
Node.js TCP client and server example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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'); | |
}); |
you try to connect to another pc port? if yes, make sure to allow inbound firewall
this gist was really helpful for me, thank you dude
same! thank you!
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
require("net") is not working in 16.13.1
when i move to 18.x now it says digital envelope routines unsupported
.......