File server.js
:
'use strict';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
const PORT = 3000;
server.on('message', (msg, info) => {
console.log(`Message ${msg} from ${info.address}:${info.port}`);
});
server.bind(PORT);
File client.js
:
'use strict';
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var SERVER = 'localhost';
var PORT = 3000;
process.stdin.on('data', (data) => {
console.log(data.toString('utf8'));
client.send(data, 0, data.length, PORT, SERVER, (err, bytes) => {
if (err) {
console.error(err);
} else {
console.log('successful');
}
});
});
Sample output
Server:
Message hello
from 127.0.0.1:59216
Message world
from 127.0.0.1:59216
Client:
hello
hello
successful
world
world
successful