-
-
Save tomfun/67396f4fd59405a57293 to your computer and use it in GitHub Desktop.
Node.js tcp client and server example
This file contains hidden or 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
/** | |
env SERVER=1 node 3.js | |
http://joxi.ru/n2YYBPdcjnbK42 | |
http://joxi.ru/DmB74bJFN8JoB2 | |
*/ | |
/* | |
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 path = require('path'); | |
var fs = require('fs'); | |
var PATH = '\\\\.\\pipe\\' + /*process.cwd(),*/ 'myctl'; // '/tmp/3.test.sock' | |
var net = require('net'); | |
if (process.env.SERVER) { | |
if (fs.existsSync(PATH)) { | |
console.log('remove...'); | |
fs.unlinkSync(PATH); | |
} | |
var server = net.createServer(function (socket) { | |
socket.on('data', function(data) { | |
console.log('server: ' + data); | |
//client.destroy(); // kill client after server's response | |
}); | |
socket.write('Echo server\r\n'); | |
//socket.pipe(socket); | |
}); | |
console.log('starting...', PATH); | |
//server.listen(1337, '192.168.88.108'); | |
server.listen(PATH); | |
} | |
/* | |
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(); | |
var t1 = process.hrtime(); | |
//client.connect(1337, '192.168.88.108', function() { | |
client.connect(PATH, function() { | |
console.log('Connected'); | |
client.write('Hello, server! Love, Client.'); | |
}); | |
client.on('data', function(data) { | |
console.log('Received: ' + data); | |
const t2 = process.hrtime(t1); | |
console.log('from connect to recieve: ', t2[0], 's ', t2[1] / 1000000, ' ms'); | |
client.destroy(); // kill client after server's response | |
}); | |
client.on('close', function() { | |
console.log('Connection closed'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just show UNIX pipe work