Node.js uses the type net.Socket
.
It uses an event driven callback model, so data ead
is handled by Socket.on('data', function(data)) {...}
.
The client is
EchoClient.js illustrates this:
//from https://www.hacksparrow.com/nodejs/tcp-socket-programming-in-node-js.html
var net = require('net');
if (process.argv.length < 3) {
concole.log('Usage: command hostname')
process.exit(1)
}
hostname = process.argv[2]
var HOST = hostname;
var PORT = 2000;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
//console.log('CONNECTED TO: ' + HOST + ':' + PORT);
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log(`Echoed: '${data}'`);
process.stdout.write("Enter line:")
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
// now read from stdin and echo to/from server
const readline = require('readline');
// no newline after prompt
process.stdout.write("Enter line:")
const con = readline.createInterface({
input: process.stdin,
output: process.stdout
});
con.on('line', (input) => {
console.log(`Read line: '${input}'`);
client.write(input);
if (input == 'BYE') {
con.close()
client.destroy()
process.exit(0);
}
});
The server is pretty straightforward, following similar lines to the client: EchoServer.js illustrates this:
//from https://www.hacksparrow.com/nodejs/tcp-socket-programming-in-node-js.html
const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.on('data', function(data) {
c.write(data);
});
c.on('close', function() {
console.log('Connection closed');
});
c.on('error', function() {
c.destroy();
console.log('Connection error');
});
});
server.on('error', (err) => {
throw err;
});
server.listen(2000, () => {
console.log('server bound');
});
Copyright © Jan Newmarch, jan@newmarch.name
" Network Programming using Java, Go, Python, Rust, JavaScript and Julia"
by
Jan Newmarch
is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
.
Based on a work at
https://jan.newmarch.name/NetworkProgramming/
.