创建 UDP 服务器
const dgram = require('dgram'); const server = dgram.createSocket('udp4'); // 创建 message 事件的接收器 server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); // 服务器发消息 server.send("message '" + msg + "' received!", rinfo.port, rinfo.address); }); // 设置侦听事件的响应 server.on('listening', () => { const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); // 绑定到端口上 server.bind(4333);
创建 UDP 客户端
const dgram = require('dgram'); const client = dgram.createSocket('udp4'); const message = Buffer.from('Udp 客户端请求'); // 发送消息 client.send(message, 4333, 'localhost', (err) => { client.close(); }); // 客户端收消息 client.on("message", (msg, rinfo) => { console.log(`client got: ${msg} from ${rinfo.address}:${rinfo.port}`); console.log("message from server, received"); console.log("message is" + msg); client.close(); });