Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active May 31, 2018 08:26
Show Gist options
  • Save bellbind/ec9308b909d56eaacdf5d5c050c782a3 to your computer and use it in GitHub Desktop.
Save bellbind/ec9308b909d56eaacdf5d5c050c782a3 to your computer and use it in GitHub Desktop.
[nodejs] TCP example
"use strict";
const net = require("net");
const port = process.env.PORT || 44444;
const once = !!process.env.ONCE || false;
function echo(socket) {
const server = this;
const {remoteAddress, remoteFamily, remotePort} = socket;
const bufs = [];
socket.on("data", buf => bufs.push(buf)).once("end", _ => {
const msg = Buffer.concat(bufs);
console.log(msg.toString(), {remoteAddress, remoteFamily, remotePort});
socket.end(Buffer.from(`accept: ${msg.toString()}`));
if (once) server.close();
});
};
const server = net.createServer({allowHalfOpen: true}, echo);
server.listen(port, _ => {
const address = server.address();
console.log(`listen on`, address);
});
"use strict";
const net = require("net");
const host = process.env.HOST || "localhost";
const port = process.env.PORT || 44444;
const msg = process.env.MSG || "Hello TCP";
const addr = {}, bufs = [];
const socket = net.createConnection({allowHalfOpen: true, port, host}, _ => {
const {remoteAddress, remoteFamily, remotePort} = socket;
Object.assign(addr, {remoteAddress, remoteFamily, remotePort});
socket.end(Buffer.from(msg));
}).on("data", buf => bufs.push(buf)).once("end", _ => {
const msg = Buffer.concat(bufs);
console.log(msg.toString(), addr);
});
@bellbind
Copy link
Author

Compare with the UDP code: https://gist.github.com/bellbind/8b4d02adb3672df400280c3a6df68a91

[play on localhost]

server:

PORT=44444 node tcp-echo.js

client:

PORT=44444 MSG="Hello TCP" node tcp-send.js

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