Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created August 18, 2016 10:52
Show Gist options
  • Save umidjons/d7aa7fdbfa13c3932524c420bb6f9953 to your computer and use it in GitHub Desktop.
Save umidjons/d7aa7fdbfa13c3932524c420bb6f9953 to your computer and use it in GitHub Desktop.
UDP Client/Server example

UDP Client/Server example

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment