Esempio n. 1
0
        /// <summary>
        /// 소켓 메세지 보내기
        /// </summary>
        public void SendMessage(IMessage obj)
        {
            if (false == socketClient.IsConnected())
            {
                // block
                socketClient.SendSyncConnect();
            }

            if (!ProtoDic.ContainProtoType(obj.GetType()))
            {
                Debug.LogError("알 수 없는 프로토콜 유형");
                return;
            }
            ByteBuffer buff    = new ByteBuffer();
            int        protoId = ProtoDic.GetProtoIdByProtoType(obj.GetType());

            byte[] result;
            using (MemoryStream ms = new MemoryStream())
            {
                obj.WriteTo(ms);
                result = ms.ToArray();
            }

            UInt16 lengh = (UInt16)(result.Length + 2);

            Debug.Log("lengh" + lengh + ",protoId" + protoId);
            buff.WriteShort((UInt16)lengh);

            buff.WriteShort((UInt16)protoId);
            buff.WriteBytes(result);
            SendMessage(buff);
        }
        /// <summary>
        /// 发送SOCKET消息
        /// </summary>
        public void SendMessage(IMessage obj)
        {
            if (!ProtoDic.ContainProtoType(obj.GetType()))
            {
                Debug.LogError("不存协议类型");
                return;
            }
            ByteBuffer buff    = new ByteBuffer();
            int        protoId = ProtoDic.GetProtoIdByProtoType(obj.GetType());

            byte[] result;
            using (MemoryStream ms = new MemoryStream())
            {
                obj.WriteTo(ms);
                result = ms.ToArray();
            }

            UInt16 lengh = (UInt16)(result.Length + 2);

            Debug.Log("lengh" + lengh + ",protoId" + protoId);
            buff.WriteShort((UInt16)lengh);

            buff.WriteShort((UInt16)protoId);
            buff.WriteBytes(result);
            SendMessage(buff);
        }
Esempio n. 3
0
    public new void ProcessReceivedMessage(byte[] bytes)
    {
        // parse to base message.
        var message = BaseMessage.Parser.ParseFrom(bytes);

        // get target message info.
        var           type          = ProtoDic.GetProtoTypeByProtoId(message.Id);
        MessageParser messageParser = ProtoDic.GetMessageParser(type.TypeHandle);

        // convert to target message object.
        object target = messageParser.ParseFrom(message.Data);

        List <Action <object> > list = null;

        if (_MessageCallbacks.TryGetValue(type, out list))
        {
            if (list == null || list.Count == 0)
            {
                Console.WriteLine("list == null || list.Count == 0");
                return;
            }

            for (int i = 0, length = list.Count; i < length; i++)
            {
                int index = i;
                //Loom.QueueOnMainThread(() =>
                //{
                list[index](target);
                //});
            }
        }
    }
Esempio n. 4
0
        void ProcessReceivedMessage(byte[] bytes, TcpClient client)
        {
            // parse to base message.
            var message = BaseMessage.Parser.ParseFrom(bytes);

            // get target message info.
            var type = ProtoDic.GetProtoTypeByProtoId(message.Id);

            Console.WriteLine("received data type=" + type);
            MessageParser messageParser = ProtoDic.GetMessageParser(type.TypeHandle);

            // convert to target message object.
            object target = messageParser.ParseFrom(message.Data);

            List <Action <object, TcpClient> > list = null;

            if (_MessageCallbacks.TryGetValue(type, out list))
            {
                if (list == null || list.Count == 0)
                {
                    Console.WriteLine("list == null || list.Count == 0");
                    return;
                }

                for (int i = 0, length = list.Count; i < length; i++)
                {
                    list[i](target, client);
                }
            }
        }
Esempio n. 5
0
        public void Send <T>(T message, TcpClient client)
            where T : IMessage
        {
            if (client == null)
            {
                return;
            }
            BaseMessage m    = new BaseMessage();
            var         type = typeof(T);

            Console.WriteLine("send data type=" + type);
            m.Id = ProtoDic.GetProtoIdByProtoType(type);
            byte[] bytes = message.ToByteArray();
            m.Data = ByteString.CopyFrom(bytes);
            try
            {
                bytes = m.ToByteArray();
                client.GetStream().Write(bytes, 0, bytes.Length);
            }
            catch (Exception ex)
            {
                Disconnect(client);
                Console.WriteLine("ex=" + ex.Message + LogUtil.GetStackTraceModelName());
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 派发协议
        /// </summary>
        /// <param name="protoId"></param>
        /// <param name="buff"></param>
        public void DispatchProto(int protoId, ByteBuffer buff)
        {
            if (!ProtoDic.ContainProtoId(protoId))
            {
                Debug.LogError("未知协议号");
                return;
            }
            Type   protoType = ProtoDic.GetProtoTypeByProtoId(protoId);
            object toc       = ProtoBuf.Serializer.Deserialize(protoType, new MemoryStream(buff.ReadBytes()));

            sEvents.Enqueue(new KeyValuePair <Type, object>(protoType, toc));
        }
    /// <summary>
    /// 处理服务器发过来的消息
    /// </summary>
    /// <param name="protoId"></param>
    /// <param name="obj"></param>
    public void DispatchProto(int protoId, object obj)
    {
        Type protoType = ProtoDic.GetProtoTypeByProtoId(protoId);

        try
        {
            sEvents.Enqueue(new KeyValuePair <Type, object>(protoType, obj));
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.ToString());
        }
    }
Esempio n. 8
0
        private static void SendMessage(object obj, Socket clientSocket)
        {
            MemoryStream ms = new MemoryStream();

            ProtoBuf.Serializer.Serialize(ms, obj);
            ByteBuffer buff    = new ByteBuffer();
            Type       type    = obj.GetType();
            int        protoId = ProtoDic.GetProtoIdByProtoType(type);

            buff.WriteShort((ushort)protoId);
            buff.WriteBytes(ms.ToArray());
            clientSocket.Send(WriteMessage(buff.ToBytes()));
        }
Esempio n. 9
0
        /// <summary>
        /// 发送SOCKET消息
        /// </summary>
        public void SendMessage(object obj)
        {
            if (!ProtoDic.ContainProtoType(obj.GetType()))
            {
                Debug.LogError("不存协议类型");
                return;
            }
            ByteBuffer buff    = new ByteBuffer();
            int        protoId = ProtoDic.GetProtoIdByProtoType(obj.GetType());

            buff.WriteShort((ushort)protoId);
            MemoryStream ms = new MemoryStream();

            ProtoBuf.Serializer.Serialize(ms, obj);
            byte[] result = ms.ToArray();
            buff.WriteBytes(result);
            SendMessage(buff);
        }
        /// <summary>
        /// 派发协议
        /// </summary>
        /// <param name="protoId"></param>
        /// <param name="buff"></param>
        public void DispatchProto(int protoId, byte[] buff)
        {
            if (!ProtoDic.ContainProtoId(protoId))
            {
                Debug.LogError("未知协议号");
                return;
            }
            Type protoType = ProtoDic.GetProtoTypeByProtoId(protoId);

            try
            {
                MessageParser messageParser = ProtoDic.GetMessageParser(protoType.TypeHandle);
                object        toc           = messageParser.ParseFrom(buff);
                sEvents.Enqueue(new KeyValuePair <Type, object>(protoType, toc));
            }
            catch
            {
                Debug.Log("DispatchProto Error:" + protoType.ToString());
            }
        }
Esempio n. 11
0
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="obj"></param>
    public void SendMessage(object obj)
    {
        if (!ProtoDic.isContainProtoType(obj.GetType()))
        {
            Debug.LogError("协议类型没有注册");
            return;
        }
        ByteBuffer buff    = new ByteBuffer();
        int        protoId = ProtoDic.GetProtoIdByProtoType(obj.GetType());

        using (MemoryStream ms = new MemoryStream())
        {
            ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(ms, obj);
            byte[] msg = ms.ToArray();
            buff.WriteShort((ushort)ms.Length); //消息长度
            buff.WriteShort((ushort)protoId);   //消息号
            buff.WriteBytes(msg);               //消息
            socketClient.SendMessage(buff);
        }
    }
Esempio n. 12
0
    public override void Send <T>(T message)
    {
        if (_TcpClient == null)
        {
            return;
        }
        BaseMessage m = new BaseMessage();

        m.Id = ProtoDic.GetProtoIdByProtoType(typeof(T));
        byte[] bytes = message.ToByteArray();
        m.Data = ByteString.CopyFrom(bytes);
        try
        {
            bytes = m.ToByteArray();
            _TcpClient.GetStream().Write(bytes, 0, bytes.Length);
        }
        catch (Exception ex)
        {
            Debug.Log("ex=" + ex.Message);
        }
    }
Esempio n. 13
0
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;

            while (true)
            {
                try
                {
                    int receiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息, 长度为{1}", myClientSocket.RemoteEndPoint.ToString(), receiveNumber);
                    ByteBuffer buff    = new ByteBuffer(result);
                    int        len     = buff.ReadShort();
                    int        protoId = buff.ReadShort();
                    if (!ProtoDic.ContainProtoId(protoId))
                    {
                        Console.WriteLine("未知协议号");
                        return;
                    }
                    if (protoId == 1003)
                    {
                        TosChat tos = ProtoBuf.Serializer.Deserialize <TosChat>(new MemoryStream(buff.ReadBytes()));
                        Console.WriteLine(tos.name + "         " + tos.content);
                        TocChat toc = new TocChat();
                        toc.name    = "服务端:";
                        toc.content = tos.content;
                        SendMessage(toc, myClientSocket);
                    }
                    else if (protoId == 1002)
                    {
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
 /// <summary>
 /// 处理字节数据
 /// </summary>
 /// <param name="bytes"></param>
 /// <param name="length"></param>
 private void OnReceive(byte[] bytes, int length)
 {
     memoryStream.Seek(0, SeekOrigin.End);
     memoryStream.Write(bytes, 0, length);
     memoryStream.Seek(0, SeekOrigin.Begin);
     while (RemainingBytes() > 4)
     {
         int msglen  = reader.ReadUInt16();
         int protoId = reader.ReadUInt16();
         Debug.Log("收到消息号---" + protoId);
         if (RemainingBytes() >= msglen)
         {
             if (ProtoDic.isContainProtoId(protoId))
             {
                 Type protoType = ProtoDic.GetProtoTypeByProtoId(protoId);
                 using (MemoryStream ms = new MemoryStream(reader.ReadBytes(msglen)))
                 {
                     object o = ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(ms, null, protoType);
                     NetManager.Instance.DispatchProto(protoId, o);
                 }
             }
             else
             {
                 reader.ReadBytes(msglen);
                 Debug.LogError("消息号--" + protoId + "--不存在");
             }
         }
         else
         {
             memoryStream.Position -= 4;
             break;
         }
     }
     byte[] leftover = reader.ReadBytes((int)RemainingBytes());
     memoryStream.SetLength(0);//这句必须有
     memoryStream.Write(leftover, 0, leftover.Length);
 }
Esempio n. 15
0
        public void Send <T>(T message, int userId)
            where T : IMessage
        {
            if (_Server == null)
            {
                return;
            }
            BaseMessage m = new BaseMessage();

            m.Id = ProtoDic.GetProtoIdByProtoType(typeof(T));
            byte[] bytes = message.ToByteArray();
            m.Data = ByteString.CopyFrom(bytes);
            try
            {
                bytes = m.ToByteArray();
                var token = Facade.Instance.GetClient(userId);
                Console.WriteLine("send message to token._IP=" + token._GameIp);
                _Server.Send(bytes, bytes.Length, token._GameIp);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex=" + ex.Message);
            }
        }
Esempio n. 16
0
        void OnReceivedGameMsg(byte[] msg, IPEndPoint ip)
        {
            // parse to base message.
            var message = BaseMessage.Parser.ParseFrom(msg);

            // get target message info.
            var type = ProtoDic.GetProtoTypeByProtoId(message.Id);

            if (type == typeof(UDPGameStart))
            {
                MessageParser messageParser = ProtoDic.GetMessageParser(type.TypeHandle);
                // convert to target message object.
                UDPGameStart target = messageParser.ParseFrom(message.Data) as UDPGameStart;
                if (target != null)
                {
                    if (_GatePlayerInfos.ContainsKey(target.UserId))
                    {
                        var info = _GatePlayerInfos[target.UserId];
                        info._UserToken._GameIp         = ip;
                        _GatePlayerInfos[target.UserId] = info;
                    }

                    for (int i = 0, length = _GameRooms.Count; i < length; i++)
                    {
                        var room = _GameRooms[i];
                        for (int j = 0, max = room._UserIds.Length; j < max; j++)
                        {
                            if (room._UserIds[j] == target.UserId)
                            {
                                room.PlayerReady(target.UserId, ip);
                                return;
                            }
                        }
                    }
                }
                return;
            }

            int userId = 0;
            // find client
            var e = _GatePlayerInfos.GetEnumerator();

            while (e.MoveNext())
            {
                if (e.Current.Value._UserToken._GameIp.ToString() == ip.ToString())
                {
                    userId = e.Current.Value.UserId;
                }
            }
            if (userId != 0)
            {
                for (int i = 0, length = _GameRooms.Count; i < length; i++)
                {
                    var room = _GameRooms[i];
                    for (int j = 0, max = room._UserIds.Length; j < max; j++)
                    {
                        if (room._UserIds[j] == userId)
                        {
                            room.Receive(msg);
                            return;
                        }
                    }
                }
            }
        }