TCP echo server for Node.js
Usage
- 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
npx https://gist.github.com/kfox/1280c2f0ee8324067dba15300e0f2fd3
netcat
or similar: nc localhost 9000
#!/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) | |
}) |
{ | |
"name": "tcp-echo-server", | |
"version": "1.0.0", | |
"bin": "./echo.mjs" | |
} |
Doesn't work from npx for me 😢
✗ npx https://gist.github.com/kfox/1280c2f0ee8324067dba15300e0f2fd3 Need to install the following packages: tcp-echo-server@1.0.0 Ok to proceed? (y) y /var/folders/zm/m0hqdgz50n3f3h5ccv2lb49r0000gn/T/npx69462768599.sh: line 2: tcp-echo-server: command not found
Also,
npx -v === 8.13.2
You need a newer version of node
, which should also update npx
. 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:
⮑ node -v
v20.6.1
⮑ npx -v
10.1.0
⮑ npx https://gist.github.com/kfox/1280c2f0ee8324067dba15300e0f2fd3
listening on :::9000
Amazing, it works now! Super cool idea, by the way
Doesn't work from npx for me 😢
Also,
npx -v === 8.13.2