Skip to content

Instantly share code, notes, and snippets.

@kfox
Last active December 4, 2023 11:08
Show Gist options
  • Star 51 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save kfox/1280c2f0ee8324067dba15300e0f2fd3 to your computer and use it in GitHub Desktop.
Save kfox/1280c2f0ee8324067dba15300e0f2fd3 to your computer and use it in GitHub Desktop.
TCP echo server for Node.js

TCP echo server for Node.js

Usage

  1. Make sure you have a modern-ish version of Node.js installed.
  2. Type npx https://gist.github.com/kfox/1280c2f0ee8324067dba15300e0f2fd3
  3. Connect to it from a client, e.g. 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"
}
@renatoargh
Copy link

renatoargh commented Sep 13, 2023

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

@kfox
Copy link
Author

kfox commented Sep 13, 2023

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

@renatoargh
Copy link

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