服务端 server.js
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);
客户端client.js
const dgram = require("dgram");
const client = dgram.createSocket('udp4');
client.send('客户端发起的信息!', 41234, 'localhost', (err) => {
client.close();
});
https://nodejs.org/api/dgram.html#event-close