const dgram = require('node:dgram');
let ServerArr = [];
exports.NewServer = function (port = 22333, MsgFun = undefined) {
    ServerArr[ServerArr.length] = null;
    let IntServer = ServerArr.length - 1;
    ServerArr[IntServer] = dgram.createSocket('udp4');
    // 发生异常时触发
    ServerArr[IntServer].on('error', (err) => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "发生服务异常", "异常说明": err.stack })
        }
    });
    // 收到消息时触发
    ServerArr[IntServer].on('message', (msg, rinfo) => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "收到数据", "数据内容": msg, "地址信息": rinfo.address, "端口信息": rinfo.port, "整体信息": rinfo })
        }
    });
    // 启动监听时触发
    ServerArr[IntServer].on('listening', () => {
        const address = ServerArr[IntServer].address();
        if (MsgFun != undefined) {
            MsgFun({ "状态": "启动监听成功", "地址信息": address.address, "端口信息": address.port })
        }
    });
    ServerArr[IntServer].bind(port);
    return IntServer;
}
exports.ServerClose = function (IntServer) {
    ServerArr[IntServer].close();
}
exports.ServerSend = function (IntServer, data, address, port) {
    ServerArr[IntServer].send(data, port, address)
}
exports.NewClient = function (MsgFun = undefined) {
    ServerArr[ServerArr.length] = null;
    let IntServer = ServerArr.length - 1;
    ServerArr[IntServer] = dgram.createSocket('udp4');
    ServerArr[IntServer].on('close', () => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "关闭客户端" })
        }
    });
    ServerArr[IntServer].on('error', (err) => {
        if (MsgFun != undefined) {
            MsgFun({ "状态": "发生错误异常", "异常说明": err })
        }
    });
    ServerArr[IntServer].on('message', (msg, rinfo) => {
        if (msg == 'exit') {
            if (MsgFun != undefined) {
                MsgFun({ "状态": "接收数据异常" })
            }
        }
        if (MsgFun != undefined) {
            MsgFun({ "状态": "收到数据", "数据内容": msg, "地址信息": rinfo.address, "端口信息": rinfo.port, "整体信息": rinfo })
        }
    });
    if (MsgFun != undefined) {
        MsgFun({ "状态": "初始化UDP成功" })
    }
    return IntServer;
}
exports.ClientSend = function (IntServer, message, address, port, MsgFun = undefined) {
    ServerArr[IntServer].send(message, port, address, (err) => {
        if (err) {
            if (MsgFun != undefined) {
                MsgFun({ "状态": "发送数据失败", "错误原因": err })
            }
        }
        if (MsgFun != undefined) {
            MsgFun({ "状态": "发送数据成功" })
        }
    });
}
exports.ClientClose = function (IntServer) {
    ServerArr[IntServer].close();
}