Last active
May 31, 2018 08:26
-
-
Save bellbind/8b4d02adb3672df400280c3a6df68a91 to your computer and use it in GitHub Desktop.
[nodejs]UDP example
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
"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); |
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
"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}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compare with the TCP code: https://gist.github.com/bellbind/ec9308b909d56eaacdf5d5c050c782a3
[play on localhost]
server:
client: