udp plugin for egg.
$ npm i egg-udp --save
// {app_root}/config/plugin.js
exports.udp = {
enable: true,
package: 'egg-udp',
};
// {app_root}/config/config.default.js
exports.udp = {
port: 5000,
};
see config/config.default.js for more detail.
// {app_root}/app/router.ts(or router.js)
app.udp.handle('proxy.handle');
-
This is the example for javascript.
// {app_root}/app/udp/controller/proxy.js module.exports = app => { return { async handle(udp) { udp.on('error', (err) => { console.log(`udp error:\n${err.stack}`); }); udp.on('message', (msg, rinfo) => { console.log(`udp server got: ${msg.toString()} from ${rinfo.address}:${rinfo.port}`); }); udp.on('listening', () => { const address = udp.address(); console.log(`udp listening ${address.address}:${address.port}`); }); }, }; };
-
This is the example for typescript.
// {app_root}/app/udp/controller/proxy.ts import { Application } from 'egg'; import { Socket } from 'dgram'; interface Rinfo { address: string, family: string, port: number, size: number, } export default (app: Application) => { return { async handle(udp: Socket) { udp.on('error', (err) => { console.log(`udp error:\n${err.stack}`); }); udp.on('message', (msg, rinfo: Rinfo) => { console.log(`udp server got: ${msg.toString()} from ${rinfo.address}:${rinfo.port}`); }); udp.on('listening', () => { const address = udp.address(); console.log(`udp listening ${address.address}:${address.port}`); }); }, }; };
// Test udp server by Linux
$ echo "2019-05-20T15:30:57 testlog" | nc -u -w1 127.0.0.1 5000
// Check it in server log
udp server got: 2019-05-20T15:30:57 testlog from 127.0.0.1:5000