适当的错误处理和交叉引用

时间:2018-06-20 16:41:47

标签: javascript node.js sockets

下面的代码返回“ goN不是一个函数”错误。如何制作适当的错误处理程序,如果发生错误,我们需要删除一个旧对象,而是创建一个新对象?

主要模块udpSocket.js:

const udp = require('dgram');
const goN = require('./goNext').goNext;
class udpSocket {
constructor(config){
    this.config = config;
    this.socket = udp.createSocket('udp4');
    this.socket.on('message', (buf) => {
        this.socket.send(buf, this.config.outPort);
    });

    this.socket.on('error', (err) => {
        console.log(err);
        goN(this.socket, this.config.host);
    });
}

start(){
    this.socket.bind(this.config.port, this.config.host, (err) => {
        if (err){
            console.error(err);
            goN(this.socket, this.config.host);
        } else {
            this.socket.send('test', this.config.outPort, this.config.host, (err) => {
                if (err) {
                    console.error(err);
                    goN(this.socket, this.config.host);
                } else {
                    console.log('UDP server up and running on '+this.config.port+' inPort, '+this.config.outPort+' outPort');
                }
            });
        }
    });
}

close(){
    this.socket.close( () => {
        ports.add({"in": this.config.port, "out": this.config.outPort});
        delete this.socket;
    });
}
}
module.exports = udpSocket;

goNext.js:

const udpSocket = require('./udpSocket');
module.exports.goNext = (socket, host) => {
    if (socket != null){ delete socket; }
    if (ports.length > 0){
        let pp = ports.shift();
        let server = new udpSocket({
            port: pp.in,
            outPort: pp.out,
            host: host
        });
        sockets.set(pp.in, server);
        server.start();
    } else {
        console.log('no sockets left');
        process.exit(1);
    }
}

wrapper.js

const config =  require('./config').udp;
const goNext = require('./lib/goNext').goNext;
const List = require('collections/list');
global.ports = new List(config.ports);
global.sockets = new Map();

goNext(null, config.host);
goNext(null, config.host);