Last active
May 31, 2018 08:26
-
-
Save bellbind/ec9308b909d56eaacdf5d5c050c782a3 to your computer and use it in GitHub Desktop.
[nodejs] TCP 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
"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); | |
}); |
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
"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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compare with the UDP code: https://gist.github.com/bellbind/8b4d02adb3672df400280c3a6df68a91
[play on localhost]
server:
client: