Last active
February 10, 2022 23:56
-
-
Save haydnba/82e2aca475bdb6710b5d77ae0ee92324 to your computer and use it in GitHub Desktop.
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
import * as net from 'net'; | |
import * as rl from 'readline'; | |
import assert from 'assert/strict'; | |
const [ COMMAND, PORT, HOST ] = process.argv.splice(2); | |
try { | |
assert.strictEqual( | |
['open', 'host'].includes(COMMAND), | |
true, | |
'Valid commands: "host <port>", "open <port> <host?>"' | |
); | |
const run = { open, host }; | |
run[COMMAND](); | |
} catch (err) { | |
process.stderr.write(err.message + '\n'); | |
} | |
function open () { | |
const client = net.createConnection({ host: HOST | 'localhost', port: Number(PORT) }); | |
const readline = rl.createInterface({ input: process.stdin }); | |
client | |
.on('connect', handleOpen) | |
.on('data', handleData) | |
.on('error', handleError) | |
.once('end', handleClose); | |
readline.on('line', line => client.write(line)); | |
function handleOpen () { | |
process.stdout.write('connected!' + '\n'); | |
}; | |
function handleData (data) { | |
process.stdout.write('> ' + data + '\n'); | |
}; | |
function handleError (err) { | |
process.stderr.write('connection error: ' + err.message + '\n'); | |
process.exit(1); | |
}; | |
function handleClose () { | |
process.stdout.write('disonnected!' + '\n'); | |
}; | |
} | |
function host () { | |
const server = net.createServer(); | |
const handler = socket => { | |
var addr = socket.remoteAddress + ':' + socket.remotePort; | |
process.stdout.write('new connection: ' + addr + '\n'); | |
socket | |
.on('data', handleData) | |
.on('error', handleError) | |
.on('close', handleClose); | |
function handleData (data) { | |
process.stdout.write('echo: ' + data + '\n'); | |
socket.write(data); | |
}; | |
function handleError (err) { | |
process.stdout.write('error: ' + err.message + '\n'); | |
}; | |
function handleClose () { | |
process.stdout.write('connection closed: ' + addr + '\n'); | |
}; | |
}; | |
server | |
.on('connection', handler) | |
.on('error', console.error); | |
server.listen( | |
Number(PORT) || 9000, | |
() => console.info('server listening on', PORT || 9000) | |
); | |
} |
Author
haydnba
commented
Feb 10, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment