当前位置:   article > 正文

Unity + Socket + Protobuf+异步+粘包拆包断包 之 二_unity socket protobuf处理数据

unity socket protobuf处理数据

上章讲了SocketClinet的结构这次讲一讲怎么使用它。

  • 我们新建一个SocketManager 来管理SocketClinet.

    SocketManager 是个单例,就不讲单例的知识点,想了解的可以去百度。
    初始化时 创建一个Socket Clinet

		public void Init(string address,int port)
        {
            this.SocketClient = new SocketClient(address, port);
            this.InitData();
        }
        
		private void InitData()
        {
            Instance.SocketClient.ConnectedAction = HeartManager.Instance.CToSDeviceCheck;
            this.SocketClient.ReceiveMessageCompleted += (s, e) =>
            {
                var rmc = e as SocketEventArgs;
                if (rmc == null) return;
                var data = rmc.Data as byte[];
                if (data != null)
                {
                    ProtobufEncoding.Instance.DecodeAsync(data);
                }
            };
            this.SocketClient.SendConnect();
            this.LoadSocketMono();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

ConnectedAction 函数 时用来连接服务器成功后,检测我们的设备ID的 ,此处可以忽略!!!!!
ProtobufEncoding.Instance.DecodeAsync(data); 是Protobuff的消息体处理方法。

  • 我们在初始化的时候同时会创建一个Gameobject对象,挂载脚本SocketMono.cs
		 private void LoadSocketMono()
        {
            UnityEngine.GameObject go = new UnityEngine.GameObject("SocketMono");
            go.AddComponent<SocketMono>();
        }
  • 1
  • 2
  • 3
  • 4
  • 5

SocketMono是继承MonoBehaviour的,它会处理一些需要用到MonoBehaviour的函数。

  • 下面还有一些发消息,处理消息,重连的函数 就不细讲,着重将一些接受处理消息
		public void DispatchProto(Message result)
        {
            //"[DispatchProto] result.Event :{0}", result.Event);

            if (!ProtoDic.Instance.ContainProtoId((int)result.Event))
            {
                //TraceWarning("未知协议号");
                return;
            }
            Type protoType = ProtoDic.Instance.GetProtoTypeByProtoId((int)result.Event);

            try
            {
                sEvents.Enqueue(result);
            }
            catch
            {
                //("DispatchProto Error:" + protoType.ToString());
            }
        }

        public void UpdateProto()
        {
            if (isQuit)
            {
                return;
            }
            if (sEvents.Count > 0)
            {
                while (sEvents.Count > 0)
                {
                    Message _event = sEvents.Dequeue();
                    if (_handlerDic.ContainsKey(_event.Event))
                    {
                        _handlerDic[_event.Event](_event);
                    }
                }
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

此处因为消息是先进先出,所以需要把消息放入队列中,然后update去处理。

下面是SocketManager详细代码:

using Com.Yy.Control.Proto;
using Google.Protobuf;
using System;
using System.Collections.Generic;

namespace YY.SocketClient
{
    public class SocketManager 
    {

        private static SocketManager instance;
        public static SocketManager Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new SocketManager();
                }
                return instance;
            }
        }
        private bool isQuit = false;

        private static Queue<Message> sEvents = new Queue<Message>();
        private Dictionary<Event, Action<Message>> _handlerDic = new Dictionary<Event, Action<Message>>();
        public SocketClient SocketClient { get; private set; }
        public SocketManager()
        {
            isQuit = false;
        }

        public void Init(string address,int port)
        {
            this.SocketClient = new SocketClient(address, port);
            this.InitData();
        }

        private void InitData()
        {
            Instance.SocketClient.ConnectedAction = HeartManager.Instance.CToSDeviceCheck;
            this.SocketClient.ReceiveMessageCompleted += (s, e) =>
            {
                var rmc = e as SocketEventArgs;
                if (rmc == null) return;
                var data = rmc.Data as byte[];
                if (data != null)
                {
                    ProtobufEncoding.Instance.DecodeAsync(data);
                }
            };
            this.SocketClient.SendConnect();
            this.LoadSocketMono();
        }

        private void LoadSocketMono()
        {
            UnityEngine.GameObject go = new UnityEngine.GameObject("SocketMono");
            go.AddComponent<SocketMono>();
        }
        public void SendMessage(IMessage obj, int typeID)
        {
            this.SendMessage(obj as Message);
        }

        /// <summary>
        /// 发送数据给服务器
        /// </summary>
        public void SendMessage(IMessage msg)
        {
            if (null == msg)
            {
                //"消息不能为空!");
                return;
            }
            Message message = msg as Message;
            //"SendMessage Event:{0},DeviceNumber:{1}", message.Event, message.DeviceNumber);

            this.SocketClient.OnSendMessage(ProtobufEncoding.Instance.Encode(msg));
        }

        public void Reconnect()
        {
            if(SocketClient!= null)
            {
                ProtobufEncoding.Instance.ResetBuffer();
                SocketClient.Reconnect();
            }           
        }

        /// <summary>
        /// 派发协议
        /// </summary>
        /// <param name="buff"></param>
        public void DispatchProto(byte[] buff)
        {
            var result = ProtobufEncoding.Instance.Decode(buff) as Message;
            this.DispatchProto(result);
        }
        public void DispatchProto(Message result)
        {
            //"[DispatchProto] result.Event :{0}", result.Event);

            if (!ProtoDic.Instance.ContainProtoId((int)result.Event))
            {
                //TraceWarning("未知协议号");
                return;
            }
            Type protoType = ProtoDic.Instance.GetProtoTypeByProtoId((int)result.Event);

            try
            {
                sEvents.Enqueue(result);
            }
            catch
            {
                //("DispatchProto Error:" + protoType.ToString());
            }
        }

        public void UpdateProto()
        {
            if (isQuit)
            {
                return;
            }
            if (sEvents.Count > 0)
            {
                while (sEvents.Count > 0)
                {
                    Message _event = sEvents.Dequeue();
                    if (_handlerDic.ContainsKey(_event.Event))
                    {
                        _handlerDic[_event.Event](_event);
                    }
                }
            }
        }

        public void AddHandler(Event type, Action<Message> handler)
        {
            if (_handlerDic.ContainsKey(type))
            {
                _handlerDic[type] += handler;
            }
            else
            {
                _handlerDic.Add(type, handler);
            }
        }

        public void RemoveHandler(Event type, Action<Message> handler)
        {
            if (_handlerDic.ContainsKey(type))
            {
                _handlerDic[type] -= handler;
            }
        }
        public void OnApplicationQuit()
        {
            this.SocketClient.OnApplicationQuit();
            isQuit = true;
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号