All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ys.artifact-network.1.0.5.source-code.cs2.btl Maven / Gradle / Ivy

The newest version!
using System;
using System.Collections;
using System.Collections.Generic;
using Artifact.Network;
using Artifact.Network.Buffer;
using Artifact.Network.Coder;

//namespace client.network.protocol
namespace Artifact.Unity.Network
{
    public interface AbstractDTO {
        Dictionary toMap(Dictionary map);
        object forMap(Dictionary map);
    }
    <%
    for(struct in structs){
        var extends = false;
    	var extendConstant = "";
    	if(strutil.isNotBlank(struct.extendsName)){
    		extends = true;
    		extendConstant = ": " + struct.extendsName;
    	}else{
    		extends = false;
    		extendConstant = ": AbstractDTO";
    	}
    %>
    /// 
    /// ${struct.remark}
    /// 
    public class ${struct.structName} ${extendConstant}{
        <%
        for(field in struct.fields){
        %>
        /// 
        /// ${field.key.remark}
        /// 
        public ${field.value.intact} ${uf(field.key.name)} { get; set; }
        <%}%>

        <%if(extends){%>
        public override Dictionary toMap(Dictionary map){
            base.toMap(map);
        <%}else{%>
        public virtual Dictionary toMap(Dictionary map){
        <%}%>
            <%
            var hashArray = [];
            for(field in struct.fields){
            hashCode = HashUtil.javaDefaultHash(field.key.name)+"";
            if(array.contain(hashArray,hashCode)){
                println("		"+field.key.name+":HashCode重复,请重命名");
                continue;
            }else{
                array.add(hashArray,hashCode);
            }
            %>
            <%if(field.value.type == "Dictionary"){%>
            Dictionary _${field.key.name} = new Dictionary();
            foreach (KeyValuePair<${field.value.generics[0]},${field.value.generics[1]}> kv in this.${uf(field.key.name)})
            {
                _${field.key.name}.Add(DtoSerializationProvider.tryDecoder(kv.Key), DtoSerializationProvider.tryDecoder(kv.Value));
            }
            map.Add(${hashCode}, _${field.key.name});
            <%}else if(field.value.type == "List"){%>
            List _${field.key.name} = new List();
            foreach (${field.value.generics[0]} obj in this.${uf(field.key.name)})
            {
                _${field.key.name}.Add(DtoSerializationProvider.tryDecoder(obj));
            }
            map.Add(${hashCode}, _${field.key.name});
            <%}else{%>
            map.Add(${hashCode}, DtoSerializationProvider.tryEncoder(this.${uf(field.key.name)}));
            <%}%>
            <%}%>
            return map;
        }
        <%if(extends){%>
        public override object forMap(Dictionary map){
            base.forMap(map);
        <%}else{%>
        public virtual object forMap(Dictionary map){
        <%}%>
            <%
            for(field in struct.fields){
            hashCode = HashUtil.javaDefaultHash(field.key.name)+"";
            %>
            <%if(field.value.type == "Dictionary"){%>
            this.${uf(field.key.name)} = new ${field.value.intact}();
            foreach (KeyValuePair kv in (Dictionary)CommonTool.get(map,${hashCode},new Dictionary()))
            {
                this.${uf(field.key.name)}.Add((${field.value.generics[0]})DtoSerializationProvider.tryDecoder(kv.Key), (${field.value.generics[1]})DtoSerializationProvider.tryDecoder(kv.Value));
            }
            <%}else if(field.value.type == "List"){%>
            this.${uf(field.key.name)} = new ${field.value.intact}();
            foreach (object obj in (List)CommonTool.get(map,${hashCode},new List()))
            {
                this.${uf(field.key.name)}.Add((${field.value.generics[0]})DtoSerializationProvider.tryDecoder(obj));
            }
            <%}else{%>
            this.${uf(field.key.name)} = (${field.value.intact})DtoSerializationProvider.tryDecoder(CommonTool.get(map,${hashCode},this.${uf(field.key.name)}));
            <%}%>
            <%}%>
            return this;
        }
    }

    <%}%>








    <%for(module in modules){%>
    public class ${module.name}Module{
        <%for(send in module.protocolSends){%>
        public const int ${ccu(send.requestName)} = ${ProtocolUtil.getCommandId(module.id,send.id)};
        <%}%>
        <%for(push in module.protocolPushs){%>
        public const int ${ccu(push.pushName)} = ${ProtocolUtil.getCommandId(module.id,push.id)};
        <%}%>

        public static void disp(Packet packet) {
            int command = (int)packet.Head[NetworkHeader.COMMAND];
            int module = command >> 16;
            int method = module << 16 ^ command;
            switch (method) {
                <%for(send in module.protocolSends){%>
                case ${send.id}:
                    _${send.requestName}(packet);
                    break;
                <%}%>
                <%for(push in module.protocolPushs){%>
                case ${push.id}:
                    _${push.pushName}(packet);
                    break;
                <%}%>
            }
        }

        <%
        for(send in module.protocolSends){
            var parameter = "";
            var values = "";
            var hashArray = [];
            for(rp in send.requestParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key)+"";
                if(array.contain(hashArray,hashCode)){
                    println("		"+rp.key+":HashCode重复,请重命名");
                    continue;
                }else{
                    array.add(hashArray,hashCode);
                }
                parameter = parameter + ", " + rp.value.intact + " " + rp.key;
                values = values + ", " + rp.key;
            }
        %>

        /// 
        /// ${send.remark}
        /// 
        public static void ${send.requestName}(NetClient client${parameter},${uf(send.requestName)}Listener listener) {
            Packet packet = new Packet();
            string messageId = System.Guid.NewGuid().ToString("N");
            packet.Head.Add(NetworkHeader.ID, messageId);
            packet.Head.Add(NetworkHeader.COMMAND, ${ProtocolUtil.getCommandId(module.id,send.id)});
            packet.Head.Add(NetworkHeader.MODULE, ${module.id});
            packet.Head.Add(NetworkHeader.METHOD, ${send.id});
            packet.Head.Add(NetworkHeader.TYPE, NetworkHeader.TYPE_DEFAULT);

            <%
            for(rp in send.requestParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key);
            %>
            <%if(rp.value.type == "Dictionary"){%>
            Dictionary _${rp.key} = new Dictionary();
            foreach (KeyValuePair<${rp.value.generics[0]},${rp.value.generics[1]}> kv in ${rp.key})
            {
                _${rp.key}.Add(DtoSerializationProvider.tryDecoder(kv.Key), DtoSerializationProvider.tryDecoder(kv.Value));
            }
            packet.Body.Add(${hashCode}, _${rp.key});
            <%}else if(rp.value.type == "List"){%>
            List _${rp.key} = new List();
            foreach (${rp.value.generics[0]} obj in ${rp.key})
            {
                _${rp.key}.Add(DtoSerializationProvider.tryDecoder(obj));
            }
            packet.Body.Add(${hashCode}, _${rp.key});
            <%}else{%>
            packet.Body.Add(${hashCode}, DtoSerializationProvider.tryEncoder(${rp.key}));
            <%}%>

            <%}%>
            client.AsyncSend(packet);

            // 注册监听
            if(listener!=null){
                ProtocolLListener.registerRequestListener(messageId,listener);
            }
        }

        /// 
        /// ${send.remark}-解码
        /// 
        private static void _${send.requestName}(Packet packet) {
            string messageId = (string)packet.Head[NetworkHeader.ID];
            Delegate listener = ProtocolLListener.getRequestListener(messageId);
            if(listener!=null){
                int _code = (int)packet.Head[NetworkHeader.STATUS];
                <%for(rp in send.responseParameter){%>
                <%if(rp.value.intact == "int"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "long"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "string"){%>
                ${rp.value.intact} ${rp.key} = "";
                <%}else if(rp.value.intact == "bool"){%>
                ${rp.value.intact} ${rp.key} = false;
                <%}else{%>
                ${rp.value.intact} ${rp.key} = null;
                <%}%>
                <%}%>
                if(_code == 0)
                {
                    <%
                    values = "";
                    for(rp in send.responseParameter){
                    var hashCode = HashUtil.javaDefaultHash(rp.key);
                    values = values + ", " + rp.key;
                    %>
                    <%if(rp.value.type == "Dictionary"){%>
                    ${rp.key} = new ${rp.value.intact}();
                    foreach (KeyValuePair kv in (Dictionary)CommonTool.get(packet.Body,${hashCode},new Dictionary()))
                    {
                        ${rp.key}.Add((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(kv.Key), (${rp.value.generics[1]})DtoSerializationProvider.tryDecoder(kv.Value));
                    }
                    <%}else if(rp.value.type == "List"){%>
                    ${rp.key} = new ${rp.value.intact}();
                    foreach (object obj in (List)CommonTool.get(packet.Body,${hashCode},new List()))
                    {
                        ${rp.key}.Add((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(obj));
                    }
                    <%}else{%>
                    ${rp.key} = (${rp.value.intact})DtoSerializationProvider.tryDecoder(CommonTool.get(packet.Body,${hashCode},${rp.key}));
                    <%}%>
                    <%}%>
                }
                else
                {
                    ProtocolLListener.execErrorListener(_code, packet);
                }
                // 执行监听
                ((${uf(send.requestName)}Listener)listener)(_code${values});
                // 移除监听
                ProtocolLListener.removeRequestListener(messageId);
            }
        }

        <%
        parameter = "";
        for(rp in send.responseParameter){
        parameter = parameter + ", " + rp.value.intact + " " + rp.key;
        }
        %>
        /// 
        /// ${send.remark}-监听
        /// 
        public delegate void ${uf(send.requestName)}Listener(int _code${parameter});
        <%}%>

        <%
        for(push in module.protocolPushs){
            var parameter = "";
            var values = "";
            var hashArray = [];
            for(rp in push.pushParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key)+"";
                if(array.contain(hashArray,hashCode)){
                    println("		"+rp.key+":HashCode重复,请重命名");
                    continue;
                }else{
                    array.add(hashArray,hashCode);
                }
                parameter = parameter + ", " + rp.value.intact + " " + rp.key;
                values = values + ", " + rp.key;
            }
        %>
        /// 
        /// ${push.remark}-解码
        /// 
        private static void _${push.pushName}(Packet packet) {
            int command = (int)packet.Head[NetworkHeader.COMMAND];
            Delegate listener = ProtocolLListener.getNotifyListener(command);
            if(listener!=null){
                <%for(rp in push.pushParameter){%>
                <%if(rp.value.intact == "int"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "long"){%>
                ${rp.value.intact} ${rp.key} = 0;
                <%}else if(rp.value.intact == "string"){%>
                ${rp.value.intact} ${rp.key} = "";
                <%}else if(rp.value.intact == "bool"){%>
                ${rp.value.intact} ${rp.key} = false;
                <%}else{%>
                ${rp.value.intact} ${rp.key} = null;
                <%}%>
                <%}%>

                <%
                values = "";
                for(rp in push.pushParameter){
                var hashCode = HashUtil.javaDefaultHash(rp.key);
                values = values + rp.key;
                if(!rpLP.last){
                    values = values + " ,";
                }
                %>
                <%if(rp.value.type == "Dictionary"){%>
                ${rp.key} = new ${rp.value.intact}();
                foreach (KeyValuePair kv in (Dictionary)packet.Body[${hashCode}])
                {
                    ${rp.key}.Add((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(kv.Key), (${rp.value.generics[1]})DtoSerializationProvider.tryDecoder(kv.Value));
                }
                <%}else if(rp.value.type == "List"){%>
                ${rp.key} = new ${rp.value.intact}();
                foreach (object obj in (List)packet.Body[${hashCode}])
                {
                    ${rp.key}.Add((${rp.value.generics[0]})DtoSerializationProvider.tryDecoder(obj));
                }
                <%}else{%>
                ${rp.key} = (${rp.value.intact})DtoSerializationProvider.tryDecoder(packet.Body[${hashCode}]);
                <%}%>
                <%}%>
                // 执行监听
                ((${uf(push.pushName)}Listener)listener)(${values});
            }

        }

        <%
        parameter = "";
            for(rp in push.pushParameter){
                parameter = parameter + rp.value.intact + " " + rp.key;
                if(!rpLP.last){
                    parameter = parameter + " ,";
                }
            }
        %>

        /// 
        /// ${push.remark}-监听
        /// 
        public delegate void ${uf(push.pushName)}Listener(${parameter});
        <%}%>
    }
    <%}%>

    // 消息路由
    public static class _Dispatcher {
        public static void disp(Packet packet) {
            // 取得模块ID
            int command = (int)packet.Head[NetworkHeader.COMMAND];
            int module = command >> 16;
            switch (module)
            {
                <%for(module in modules){%>
                case ${module.id}:
                    ${module.name}Module.disp(packet);
                    break;
                <%}%>
                default:
                    break;
            }
        }
    }


    public class DtoSerializationProvider{
        private delegate AbstractDTO createDTO();

        static Dictionary cache = new Dictionary();
        static Dictionary codes = new Dictionary();
        static DtoSerializationProvider()
        {
            <%
            for(struct in structs){
            var hashCode = HashUtil.javaDefaultHash(struct.structName)+"";
            %>
            // ${struct.remark}
            cache.Add(${hashCode},() => new ${struct.structName}());
            <%}%>

            <%
            for(struct in structs){
            hashCode = HashUtil.javaDefaultHash(struct.structName)+"";
            %>
            // ${struct.remark}
            codes.Add("${struct.structName}",${hashCode});
            <%}%>
        }

        // 尝试编码
        public static object tryEncoder(object obj)
        {
            if (obj is AbstractDTO)
            {
                string typeName = obj.GetType().Name;
                if(codes.ContainsKey(typeName)){
                    int structCode = codes[typeName];
                    Dictionary dict = new Dictionary();
                    dict.Add(NetworkHeader.STRUCT_CODE,structCode);
                    return ((AbstractDTO)obj).toMap(dict);
                }
            }
            return obj;
        }

        // 尝试解码
        public static object tryDecoder(object obj)
        {
            if (obj is Dictionary)
            {
                Dictionary dict = (Dictionary)obj;
                if (dict.ContainsKey(NetworkHeader.STRUCT_CODE))
                {
                    int structCode = (int)dict[NetworkHeader.STRUCT_CODE];
                    if (DtoSerializationProvider.cache.ContainsKey(structCode))
                    {
                        AbstractDTO dto = cache[structCode]();
                        return dto.forMap(dict);
                    }
                }
            }
            return obj;
        }
    }

    /**
    public class ArtifactProtocolStreamBuffer : ArtifactStreamBuffer
    {
        public const int STRUCT_CODE = 183928832;

        public ArtifactProtocolStreamBuffer(byte[] bytes = null) : base(bytes)
        {

        }

        public override void WriteObject(object value)
        {
            if (value is AbstractDTO)
            {
                Dictionary table = new Dictionary();
                ((AbstractDTO)value).toMap(table);
                table.Add(STRUCT_CODE, DtoSerializationProvider.structCode(value.GetType().Name));
                WriteDict(table);
            }
            else
            {
                base.WriteObject(value);
            }
        }

        public override object ReadObject()
        {
            MarkReaderIndex();
            byte tag = Read();
            ResetReaderIndex();
            if (tag == ArtifactBufferCoder.DICT || ArtifactBufferCoder.DICT_SUB_TYPE.ContainsVal(tag))
            {
                Dictionary map = ReadDict();
                if (map.ContainsKey(STRUCT_CODE))
                {
                    int structCode = (int)map[STRUCT_CODE];
                    AbstractDTO dto = DtoSerializationProvider.create(structCode);
                    return dto.forMap(map);
                }
                else
                {
                    return map;
                }

            }
            else {
                return base.ReadObject();
            }
        }
    }

    public class SimpleDecoder : Decoder
    {
        public Packet Handler(NetClient client, byte[] data)
        {
            using (ByteBuffer byteBuffer = new ArtifactProtocolStreamBuffer(data))
            {
                Packet packet = new Packet();
                packet.ForByteBuff(byteBuffer);
                return packet;
            }
        }
    }

    public class SimpleEncoder : Encoder
    {
        public byte[] Handler(NetClient client, Packet packet)
        {
            using (ByteBuffer byteBuffer = new ArtifactProtocolStreamBuffer())
            {
                byteBuffer.MarkWriterIndex();
                byteBuffer.Write(new byte[4]);
                packet.ToByteBuff(byteBuffer);
                int length = (int)byteBuffer.GetLength();
                byteBuffer.ResetWriterIndex();
                byteBuffer.Write(BufferUtil.GetByte(length - 4));
                return byteBuffer.ToArray();
            }
        }
    }
    */
    public class NetworkHeader
    {
        public const int STRUCT_CODE = 183928832;


        /** 唯一表示 */
        public const int ID = 0;
        /** 命令 */
        public const int COMMAND = 1;
        /** 状态 */
        public const int STATUS = 2;
        /** 模块 */
        public const int MODULE = 3;
        /** 方法 */
        public const int METHOD = 4;
        /** 类型 */
        public const int TYPE = 5;
        /** 标签 */
        public const int TAG = 6;

        /** 后续可扩展加密方式,验证方式、校验和等等 */












        /** 类型-默认包 */
        public const int TYPE_DEFAULT = 1;
        /** 类型-心跳包 */
        public const int TYPE_HEARTBEAT = 2;
        /** 类型-确认包 */
        public const int TYPE_ACK = 3;
    }

    public delegate void ErrorListener(int _code, Packet packet);

    public class ProtocolLListener
    {

        private static Hashtable request = new Hashtable();

        private static Hashtable notify = new Hashtable();

        private static ErrorListener errorListener = null;

        public static void registerErrorListener(ErrorListener errorListener)
        {
            ProtocolLListener.errorListener = errorListener;
        }

        public static void removeErrorListener()
        {
            ProtocolLListener.errorListener = null;
        }

        public static void execErrorListener(int _code, Packet packet) {
            if (errorListener != null) {
                errorListener(_code, packet);
            }
        }

        public static void registerNotifyListener(int command, Delegate @delegate)
        {
            notify.Add(command, @delegate);
        }

        public static void registerRequestListener(string messageId, Delegate @delegate)
        {
            request.Add(messageId, @delegate);
        }

        public static void removeNotifyListener(int command)
        {
            notify.Remove(command);
        }

        public static void removeRequestListener(string messageId)
        {
            request.Remove(messageId);
        }

        public static Delegate getNotifyListener(int command)
        {
            return (Delegate)notify[command];
        }

        public static Delegate getRequestListener(string messageId)
        {
            return (Delegate)request[messageId];
        }

        public static void clearNotifyListener()
        {
            notify.Clear();
        }

        public static void clearRequestListener()
        {
            request.Clear();
        }
    }

    public class CommonTool
    {
        public static object get(Dictionary map, object key, object val)
        {
            if (map.ContainsKey(key)) {
                return map[key];
            }
            return val;
        }
    }
}