- Make sure you have a modern-ish version of Node.js installed.
- Type
npx https://gist.github.com/kfox/1280c2f0ee8324067dba15300e0f2fd3
- Connect to it from a client, e.g.
netcat
or similar:nc localhost 9000
Last active
December 4, 2023 11:08
-
-
Save kfox/1280c2f0ee8324067dba15300e0f2fd3 to your computer and use it in GitHub Desktop.
TCP echo server for Node.js
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
#!/usr/bin/env node | |
import net from 'node:net' | |
const port = process.argv[2] || 9000 | |
const server = net.createServer((connection) => { | |
const { address, port } = connection.address() | |
const socket = `${address}:${port}` | |
console.log(`${socket} - client connected`) | |
connection.on('data', (data) => { | |
console.log(`${socket} - client sent: %s`, String(data).trim()) | |
connection.write(data) | |
}) | |
connection.on('end', () => { | |
console.log(`${socket} - client disconnected`) | |
}) | |
}) | |
server.listen({ port }, () => { | |
const { address, port } = server.address() | |
console.log('listening on %s:%d', address, port) | |
}) |
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
{ | |
"name": "tcp-echo-server", | |
"version": "1.0.0", | |
"bin": "./echo.mjs" | |
} |
Amazing, it works now! Super cool idea, by the way
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need a newer version of
node
, which should also updatenpx
. I'm not sure what the minimum version numbers for each binary are, but if you are running on a more recent version it should work. I have the following versions installed: