Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active May 31, 2018 08:26
Show Gist options
  • Save bellbind/8b4d02adb3672df400280c3a6df68a91 to your computer and use it in GitHub Desktop.
Save bellbind/8b4d02adb3672df400280c3a6df68a91 to your computer and use it in GitHub Desktop.
[nodejs]UDP example
"use strict";
const dgram = require("dgram");
const port = process.env.PORT || 44444;
const once = !!process.env.ONCE || false;
const opts = {type: "udp4", reuseAddr: true};
const socket = dgram.createSocket(opts, (msg, info) => {
// msg: Buffer, info: {address, family, port, size}
console.log(msg.toString(), info);
const reply = `accept: ${msg.toString()}`;
socket.send(Buffer.from(reply), info.port, info.address, err => {
if (err) console.error(err);
if (once) socket.close();
});
}).once("listening", _ => {
// addr: {address, family, port}
const addr = socket.address();
console.log(`wait on`, addr);
}).bind(port);
"use strict";
const dgram = require("dgram");
const host = process.env.HOST || "localhost";
const port = process.env.PORT || 44444;
const msg = process.env.MSG || "Hello UDP";
const socket = dgram.createSocket("udp4", (msg, info) => {
console.log(msg.toString(), info);
socket.close();
});
socket.send(Buffer.from(msg), port, host, err => {
// called after sent
if (err) console.error(err);
console.log(`sent ${msg} to ${host}:${port}`);
});
@bellbind
Copy link
Author

bellbind commented May 28, 2016

Compare with the TCP code: https://gist.github.com/bellbind/ec9308b909d56eaacdf5d5c050c782a3

[play on localhost]

server:

PORT=44444 node udp-echo.js

client:

PORT=44444 MSG="Hello UDP" node udp-send.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment