egg-ludp
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

egg-udp

NPM version build status Known Vulnerabilities npm download

udp plugin for egg.

Install

$ npm i egg-udp --save

Usage

// {app_root}/config/plugin.js
exports.udp = {
  enable: true,
  package: 'egg-udp',
};

Configuration

// {app_root}/config/config.default.js
exports.udp = {
  port: 5000,
};

see config/config.default.js for more detail.

Example

Router example

// {app_root}/app/router.ts(or router.js)
app.udp.handle('proxy.handle');

Controller example

  • 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

// 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

License

MIT

Package Sidebar

Install

npm i egg-ludp

Weekly Downloads

1

Version

1.2.0

License

MIT

Unpacked Size

19.8 kB

Total Files

7

Last publish

Collaborators

  • soraprayer