/*
文件名:Socket.nut
路径:User/Socket/Socket.nut
创建日期:2024-12-01	14:47
文件用途:网络通信
*/
class MySocket extends Socket {

    //字符串包处理逻辑
    PackHandler = null;
    //数据流包处理逻辑
    PackBinaryHandler = null;

    State = 0;

    constructor(Ip, Port) {
        //初始化处理逻辑Map
        PackHandler = {};
        PackBinaryHandler = {};

        //先执行父类的构造函数
        base.constructor();

        //绑定回调函数
        BindFunc(SOCKET_CALLBACK_TYPE.onConnect, function() {
            State = 1;
        }.bindenv(this));
        BindFunc(SOCKET_CALLBACK_TYPE.onReceive, function(PacketId, Str) {
            // print("收到消息：" + PacketId + " " + Str);
            //如果存在对应处理逻辑
            if (PackHandler.rawin(PacketId)) {
                //将字符画序列化json
                local Jso = Json.Decode(Str);
                PackHandler[PacketId](Jso);
            }
        }.bindenv(this));
        BindFunc(SOCKET_CALLBACK_TYPE.onReceiveBinary, function(PacketId, Blob_Obj) {
            //如果存在对应处理逻辑
            if (PackBinaryHandler.rawin(PacketId)) {
                PackBinaryHandler[PacketId](Blob_Obj);
            }
        }.bindenv(this));

        Connect(Ip, Port, false);
        //注册自己到全局
        getroottable()._MySocket_ <- this;
    }

    //注册字符串包处理逻辑
    function RegisterHandler(PacketId, Func) {
        getroottable()._MySocket_.PackHandler.rawset(PacketId, Func);
    }

    //注册数据流包处理逻辑
    function RegisterBinaryHandler(PacketId, Func) {
        getroottable()._MySocket_.PackBinaryHandler.rawset(PacketId, Func);
    }

    //发包
    function Send(PacketId, Jso) {
        local SendObject;
        if (typeof Jso == "table") SendObject = Json.Encode(Jso); //table转json字符串 字符串包
        else if (typeof Jso == "blob") SendObject = Jso; //字节流包
        else SendObject = ""; //空包
        Socket_SendPacket(getroottable()._MySocket_.Client, PacketId, SendObject);
    }
}