Created
September 7, 2021 06:29
-
-
Save himalay/1ee3458c4d70732fbe67639bde9bd914 to your computer and use it in GitHub Desktop.
Simple UDP broadcaster and listener in Node.js
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
import { createSocket } from 'dgram' | |
const PORT = process.env.UDP_LISTENER_PORT || 41234 | |
const socket = createSocket('udp4') | |
const message = Buffer.from('MST_TV_SERVER') | |
socket.bind(() => { | |
socket.setBroadcast(true) | |
const broadcastInterval = setInterval(() => { | |
socket.send(message, 0, message.length, PORT, '255.255.255.255', (err) => { | |
if (err) { | |
console.error('Broadcast error:', err) | |
socket.close() | |
clearInterval(broadcastInterval) | |
} | |
}) | |
}, 1000 * 5) | |
}) |
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
import { createSocket } from 'dgram' | |
const PORT = process.env.UDP_LISTENER_PORT || 41234 | |
const server = createSocket('udp4') | |
server.on('error', (err) => { | |
console.error('Listening error:', err) | |
server.close() | |
}) | |
server.on('message', (msg, remoteInfo) => { | |
console.log(`Message: ${msg} from ${remoteInfo.address}:${remoteInfo.port}`) | |
}) | |
server.on('listening', () => { | |
const serverAddress = server.address() | |
console.log(`Listening at ${serverAddress.address}:${serverAddress.port}`) | |
}) | |
server.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
{ | |
"name": "udp", | |
"version": "1.0.0", | |
"description": "Simple UDP broadcaster and listener in Node.js", | |
"main": "listener.js", | |
"type": "module", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment