-
-
Save lqqyt2423/954dc66ce45a21d525de09535dce653f to your computer and use it in GitHub Desktop.
udp 父子进程
This file contains hidden or 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
// server.js | |
'use strict'; | |
const dgram = require('dgram'); | |
const server = dgram.createSocket('udp4'); | |
server.on('error', err => { | |
console.log(`server error:\n${err.stack}`); | |
server.close(); | |
}); | |
server.on('message', (msg, rinfo) => { | |
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); | |
}); | |
server.on('listening', () => { | |
const address = server.address(); | |
console.log(`server listening ${address.address}:${address.port}`); | |
}); | |
server.bind(41234, () => { | |
require('child_process').fork('sub.js').send('server', server); | |
}); | |
// sub.js | |
'use strict'; | |
process.on('message', (m, server) => { | |
if (m === 'server') { | |
server.on('message', (msg, rinfo) => { | |
console.log('sub'); | |
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); | |
}); | |
} | |
}); | |
// client.js | |
'use strict'; | |
const dgram = require('dgram'); | |
const client = dgram.createSocket('udp4'); | |
const message = Buffer.from('Hello World'); | |
client.send(message, 41234, 'localhost', (err) => { | |
client.close(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment