Ejemplo n.º 1
0
        public bool PushPacket(Packet packet)
        {
            if (m_Socket.IsConnected() == false)
            {
                //-- 这里应该return false,并且重新连接。
                return(false);
            }

            if (m_LogicSendHandler == null)
            {
                //-TODO: new throw
                return(false);
            }
            packet.SetPacketIndex(m_serverMsgIndex);

            // 不再检测大小了;
            int bodyLength = m_LogicSendHandler.WritePacket(packet);

            //Int32 nWriteSize = m_LogicSendHandler.WritePacket(packet);
            //if (nWriteSize != packet.GetPacketBodySize())
            //{
            //    //-TODO: log
            CommonDebugLog.LogWarning("the body length is " + bodyLength);
            //}
            return(true);
        }
Ejemplo n.º 2
0
        public bool WritePacket(ref BinaryWriter oStream)
        {
            Stream iStream         = oStream.BaseStream;
            long   packetUINT32Pos = iStream.Position;

            if (!WritePacketHeader(ref oStream))
            {
                return(false);
            }
            long lengthHeader = iStream.Length;

            if (!WritePacketBody(ref oStream))
            {
                return(false);
            }
            long  endPos       = iStream.Length;
            long  bodyLength   = endPos - sizeof(Int16);
            Int16 packetUInt32 = (Int16)bodyLength;

            try
            {
                oStream.Seek((Int32)packetUINT32Pos, SeekOrigin.Begin);
                oStream.Write(packetUInt32);
                oStream.Seek((Int32)endPos, SeekOrigin.Begin);
            }
            catch (System.Exception ex)
            {
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
            }

            return(true);
        }
Ejemplo n.º 3
0
        public static Int32 GetUTF8StringLength(string InputString)
        {
            if (string.IsNullOrEmpty(InputString))
            {
                return(0);
            }

            byte[] byteArray = null;
            try
            {
                byteArray = System.Text.Encoding.UTF8.GetBytes(InputString);
            }
            catch (System.Exception ex)
            {
                //-- log
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                return(0);
            }

            if (byteArray == null)
            {
                return(0);
            }

            return(byteArray.Length);
        }
Ejemplo n.º 4
0
        public LogicRecvBuffer GetUsedBuf()
        {
            lock (m_LockerForRecvList)
            {
                LogicRecvBuffer buffer = null;
                //-- 01. 在当前list中查找free的。
                for (Int32 index = 0; index < m_RecvList.Count; ++index, m_iUsedPos++)
                {
                    if (m_iUsedPos >= m_RecvList.Count)
                    {
                        m_iUsedPos = 0;
                    }
                    try
                    {
                        buffer = m_RecvList[m_iUsedPos];
                    }
                    catch (System.Exception ex)
                    {
                        //-- log记录异常
                        //-- 从开始找到一个可以free的。
                        CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                        m_iUsedPos = 0;
                        goto __NO_USED_LOGICSENDBUFFER;
                    }

                    if (buffer.GetUsedFlag() == false)
                    {
                        continue;
                    }

                    //-- test
                    buffer.m_indexInPool = m_iUsedPos;

                    m_iUsedPos++;
                    if (m_iUsedPos >= m_RecvList.Count)
                    {
                        m_iUsedPos = 0;
                    }


                    buffer.GetMemoryStream().Seek(0, SeekOrigin.Begin);
                    return(buffer);
                }

__NO_USED_LOGICSENDBUFFER:
                //-- 02. 没有找到,则返回null
                return(null);
            }
        }
Ejemplo n.º 5
0
        public SocketRecvBuf GetRecvBuf()
        {
            lock (m_LockerForRecvList)
            {
                SocketRecvBuf buffer = null;

                //-- 01. 在当前list中查找free的。
                for (Int32 index = 0; index < m_RecvList.Count; ++index, m_iPos++)
                {
                    if (m_iPos >= m_RecvList.Count)
                    {
                        m_iPos = 0;
                    }
                    try
                    {
                        buffer = m_RecvList[m_iPos];
                    }
                    catch (System.Exception ex)
                    {
                        //-- log记录异常
                        //-- 从开始找到一个可以free的。
                        CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                        m_iPos = 0;
                        return(null);
                    }

                    if (buffer.GetUsedFlag() == true)
                    {
                        continue;
                    }

                    buffer.Clear();

                    //-- test
                    buffer.m_indexInPool = m_iPos;

                    m_iPos++;
                    if (m_iPos >= m_RecvList.Count)
                    {
                        m_iPos = 0;
                    }

                    return(buffer);
                }

                //-- 02. 没有找到,则返回null。等待数据接收
                return(null);
            }
        }
Ejemplo n.º 6
0
 // 创建事件ID和name的映射表.
 void AddEventMapping(string name, GameEventID eventId)
 {
     if (mEventDefines.ContainsKey(name) == true)
     {
         CommonDebugLog.Log(" The event " + name + "already contains a definition for EventMapping");
     }
     else if (mEventDefines.ContainsValue(eventId) == true)
     {
         CommonDebugLog.Log(" The event " + name + "already contains a definition for EventMapping");
     }
     else
     {
         mEventDefines[name] = eventId;
     }
 }
Ejemplo n.º 7
0
 public void SeeEveryNode()
 {
     for (Int32 i = 0; i < keyList.size; ++i)
     {
         if ((bool)hashTableStatus[keyList[i]] == true)
         {
             System.Object obj = hashTableObjs[keyList[i]];
             CommonDebugLog.Log(obj.ToString());
         }
         else
         {
             System.Object obj = hashTableObjs[keyList[i]];
             CommonDebugLog.Log(obj.ToString());
         }
     }
 }
Ejemplo n.º 8
0
        void OnConnectFailed()
        {
            if (m_iTryCnt++ > TNetConfig.DEFAULT_SOCKET_CONNECT_RETRY_CNT)
            {
                m_iTryCnt = 0;
                CommonDebugLog.LogWarning("Connect failed in login!Socket Error:=(" + GetSocketError().ToString() + ")");

                if (OnFailedCallBack != null)
                {
                    OnFailedCallBack();
                    OnFailedCallBack = null;
                }

                return;
            }

            ConnectService(mStrHostName, mPortID, OnSuccessedCallBack, OnFailedCallBack);
            return;
        }
Ejemplo n.º 9
0
        public void PushPacket(Packet packet)
        {
            if (!mNetManager.IsConnected())
            {
                // 连接断开的情况下,已经不能发送协议了(先暂时加成自动重连,以后按策划需求重新规划);
                Disconnect();
                //LoginManager.GetInstance().ShowReConnectDialog();
                mFailedPacketList.Add(packet);
                return;
            }

            bool bFlag = mNetManager.PushPacket(packet);

            if (!bFlag)
            {
                CommonDebugLog.LogWarning("PushPacket Failed");
                return;
            }

            AddWatingPackets((PACKET_TYPE)packet.GetPacketID());
        }
Ejemplo n.º 10
0
        private bool WritePacketHeader(ref BinaryWriter oStream)
        {
            //-- 01. valid
            if (oStream == null)
            {
                return(false);
            }

            //-- 02. write header
            //-- PacketID_t
            //-- UINT32:m_PacketIndex[0xff000000], m_PacketStatus[0x00f00000], m_PakcetSize[0x000fffff]
            Int16 packetUInt32 = 0;

            try
            {
                oStream.Write(packetUInt32);
            }
            catch (System.Exception ex)
            {
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
            }
            try
            {
                oStream.Write((UInt16)m_PacketID);
            }
            catch (System.Exception ex)
            {
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
            }

            //PacketUtil.SetPacketIndex(ref packetUInt32, m_PacketIndex);
            //PacketUtil.SetPacketStatus(ref packetUInt32, m_PacketStatus);
            //PacketUtil.SetPacketBodyLength(ref packetUInt32, GetPacketBodySize())

            return(true);
        }
Ejemplo n.º 11
0
        public LogicRecvBuffer GetEmptyBuf()
        {
            lock (m_LockerForRecvList)
            {
                LogicRecvBuffer buffer = null;
                //-- 01. 在当前list中查找free的。
                for (Int32 index = 0; index < m_RecvList.Count; ++index, m_iEmptyPos++)
                {
                    if (m_iEmptyPos >= m_RecvList.Count)
                    {
                        m_iEmptyPos = 0;
                    }
                    try
                    {
                        buffer = m_RecvList[m_iEmptyPos];
                    }
                    catch (System.Exception ex)
                    {
                        //-- log记录异常
                        //-- 从开始找到一个可以free的。
                        CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                        m_iEmptyPos = 0;
                        goto __NEW_LOGICSENDBUFFER;
                    }

                    if (buffer.GetUsedFlag() == true)
                    {
                        continue;
                    }

                    buffer.Clear();

                    //-- test
                    buffer.m_indexInPool = m_iEmptyPos;

                    m_iEmptyPos++;
                    if (m_iEmptyPos >= m_RecvList.Count)
                    {
                        m_iEmptyPos = 0;
                    }



                    return(buffer);
                }

__NEW_LOGICSENDBUFFER:
                //-- 02. 没有找到则需要添加
                if ((buffer == null) ||
                    (buffer != null) && (buffer.GetUsedFlag() == true)
                    )
                {
                    buffer = new LogicRecvBuffer();
                    //-TODO: 下面这种情况就SB了。。。
                    if (buffer == null)
                    {
                        //-- log 怎么处理。
                    }
                    m_RecvList.Add(buffer);
                }

                buffer.Clear();
                m_iEmptyPos++;
                if (m_iEmptyPos >= m_RecvList.Count)
                {
                    m_iEmptyPos = 0;
                }

                //-- test
                buffer.m_indexInPool = (m_RecvList.Count - 1);

                return(buffer);
            } //-- end_lock(m_LockerForRecvList)
        }
Ejemplo n.º 12
0
        public bool ProcessPacket(ref byte serverMsgIndex)
        {
            if (m_LogicRecvBufQueue == null)
            {
                return(false);
            }

            //-- 判断是否有待处理的逻辑层消息缓冲数据
            LogicRecvBuffer logicRecvBuf = m_LogicRecvBufQueue.GetUsedBuf();

            if (logicRecvBuf == null)
            {
                return(true);
            }

            MemoryStream memStream = logicRecvBuf.GetMemoryStream();

            if (memStream == null)
            {
                return(false);
            }

            //-- test

            if (memStream.Length == memStream.Position)
            {
                //Console.WriteLine("memStream.Length == memStream.Position");
            }

            //-- 如果m_RemainingStream长度不为0,则之后处理的memStream的前面要加上m_RemainingStream。
            if (m_LogicRemainingBuf.Length != 0)
            {
                m_LogicRemainingBuf.Write(memStream.GetBuffer(), 0, (Int32)memStream.Length);
                Array.Clear(memStream.GetBuffer(), 0, (Int32)memStream.Length);
                memStream.Write(m_LogicRemainingBuf.GetBuffer(), 0, (Int32)m_LogicRemainingBuf.Length);
                memStream.Seek(0, SeekOrigin.Begin);
                Array.Clear(m_LogicRemainingBuf.GetBuffer(), 0, (Int32)m_LogicRemainingBuf.Length);
                m_LogicRemainingBuf.SetLength(0);
            }

            //-- memStream中的消息反序列化操作
            m_BinaryReader = new BinaryReader(memStream, System.Text.Encoding.ASCII);

            Int32      iTmpHead         = 0;
            Int32      iTmpTotalSize    = (Int32)memStream.Length;
            Int32      iTmpDeltaLenth   = 0;
            PacketID_t tmpPacketID      = (PacketID_t)PACKET_TYPE.PACKET_TYPE_NONE;
            Int16      iTmpPacketUInt32 = 0;

            while (true)
            {
                iTmpDeltaLenth = iTmpTotalSize;
                memStream.Seek(iTmpHead, SeekOrigin.Begin);
                iTmpDeltaLenth -= iTmpHead;
                UnityEngine.Debug.Log("the head is " + iTmpHead + " and the  deltaLength is " + iTmpDeltaLenth);
                //-- 如果剩余的消息长度小于Header,则放入m_RemainingStream中。等待下次帧循环来处理
                if (iTmpDeltaLenth < PacketUtil.PACKET_HEADER_SIZE)
                {
                    if (iTmpDeltaLenth > 0)
                    {
                        m_LogicRemainingBuf.Write(memStream.GetBuffer(), iTmpHead, iTmpDeltaLenth);
                    }
                    logicRecvBuf.SetUsedFlag(false);
                    break;
                }
                UnityEngine.Debug.Log("the temp delta length is " + iTmpDeltaLenth);

                iTmpPacketUInt32 = m_BinaryReader.ReadInt16();;
                //-- 消息没有接收完全。
                if (iTmpDeltaLenth < iTmpPacketUInt32)
                {
                    if (iTmpDeltaLenth > 0)
                    {
                        m_LogicRemainingBuf.Write(memStream.GetBuffer(), iTmpHead, iTmpDeltaLenth);
                    }
                    logicRecvBuf.SetUsedFlag(false);
                    Console.WriteLine("消息没有接收完全");
                    break;
                }

                try
                {
                    tmpPacketID = m_BinaryReader.ReadUInt16();
                    UnityEngine.Debug.Log("THE PACKET ID IS ====================" + tmpPacketID);
                }
                catch (System.Exception ex)
                {
                    CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                }


                Packet packet = PacketFacotry.GetInstance().CreatePacket(tmpPacketID);
                if (packet == null)
                {
                    //-- 抛出异常,根据PacketID创建Packet失败
                    //-- 略过这个出错的消息,并继续处理
                    iTmpHead += iTmpPacketUInt32;
                    CommonDebugLog.LogWarning(string.Format("CreatePacket Failed packetID = {0}", tmpPacketID));
                    //Console.WriteLine("packet == null");
                    continue;
                }

                try
                {
                    if (!packet.ReadPacketBody(m_BinaryReader, (Int16)(iTmpPacketUInt32 - 4)))
                    {
                        Console.WriteLine("packet.ReadPacketBody( m_BinaryReader) == false");
                        //-- log
                    }
                    UnityEngine.Debug.LogError("begin process packet ");
                    PacketFacotry.GetInstance().ProcessPacket(packet);

                    NetClient.GetInstance().RemoveWatingPackets((PACKET_TYPE)packet.GetPacketID());
                }
                catch (System.Exception ex)
                {
                    CommonDebugLog.LogWarning(ex.ToString());
                }

                //-- 执行成功,set iTmpHead
                iTmpHead += (Int32)(iTmpPacketUInt32);
            } //-- end_while (true)
            return(true);
        }
Ejemplo n.º 13
0
        //-- 将逻辑发送缓冲区的数据转存到net层的发送缓冲区,开启异步发送过程。并立即返回。
        public bool SendToSocketBuf(LogicSendHandler logicSendHandler)
        {
            if (logicSendHandler == null)
            {
                return(false);
            }

            //-TODO: 这里之后再考虑
            if (!IsConnected())
            {
                return(true);
            }

            int iSendLength = logicSendHandler.SendBufSize();

            if (iSendLength == 0)
            {
                return(true);
            }

            MemoryStream oMemStream = logicSendHandler.GetLogicSendBuf();

            if (oMemStream == null)
            {
                return(false);
            }

            //-- 将逻辑层缓冲区转到发送缓冲区
            //-TODO: encode type
            SocketSendBuf sendBuff = m_SocketSendBufQueue.GetBuf();

            if (sendBuff == null)
            {
                return(false);
            }
            MemoryStream sendMemStream = sendBuff.GetMemoryStream();

            if (sendMemStream == null)
            {
                return(false);
            }
            //-- oMemStream.GetBuffer()不发生new byte[]操作。
            if (oMemStream.Length == 0)
            {
                //Console.WriteLine("Error:==[logicSendHandler.SendBufSize() != 0 && oMemStream.Length == 0]");
                return(false);
            }
            try
            {
                sendMemStream.Write(oMemStream.GetBuffer(), 0, (int)oMemStream.Length);
            }
            catch (System.Exception ex)
            {
                //-- log
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                return(false);
            }
            sendBuff.SetEmptyFlag(false);
            logicSendHandler.ClearUp();

            return(Send(sendBuff));
        }
Ejemplo n.º 14
0
        public bool Connect(String ip, Int32 port, Int32 retryCnt, Int32 overTimeMillSec)
        {
            ////-- 01. 设置connect连接状态
            ////-TODO: test
            //if (netStatus == NetStatus.SOCKET_TYEP_CONNECTING ||
            //    netStatus == NetStatus.SOCKET_TYEP_GAMING)
            //{
            //    return false;
            //}

            netStatus = NetStatus.SOCKET_TYEP_CONNECTING;

            //-- 考虑在逻辑层调用这个Connect的时候,下面的两个new的问题。
            Int32 iRetryCnt = 0;

            try
            {
                IPAddress ipAddress = IPAddress.Parse(ip);
                m_IPAndPoint         = new IPEndPoint(ipAddress, port);
                m_Socket             = new Socket(m_IPAndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                m_SocketSendBufQueue = new SendBufferQueue(TNetConfig.DEFAULT_SOCKET_SEND_QUEUE_SIZE);                   //-- 多个
                m_SocketRecvBufQueue = new SocketRecvBufQueue();

                //-- test 所以设置了发送缓冲区
                //try
                //{
                //    Int32 iTest01 = (Int32)m_Socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
                //    m_Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 20);
                //    iTest01 = (Int32)m_Socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
                //}
                //catch (System.Exception ex)
                //{
                //    int i = 100; //-- for test assert
                //}
            }
            catch (System.Exception ex)
            {
                //-- log
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                return(false);
            }


__RETRY_CONNECT:
            Reset();

            SocketAsyncEventArgs connectCompleteArgs = new SocketAsyncEventArgs();;

            connectCompleteArgs.UserToken      = this;
            connectCompleteArgs.RemoteEndPoint = m_IPAndPoint;
            connectCompleteArgs.Completed     += new EventHandler <SocketAsyncEventArgs>(OnConnect);

            //-: true,io pend. waiting callback
            try
            {
                if (!m_Socket.ConnectAsync(connectCompleteArgs))
                {
                    OnConnect(null, connectCompleteArgs);
                }
            }
            catch (System.Exception ex)
            {
                if (++iRetryCnt < retryCnt)
                {
                    //log
                    goto __RETRY_CONNECT;
                }

                throw new Exception(ex.ToString());
            }

            return(true);
        }
Ejemplo n.º 15
0
        //-- 将从socket接收到的数据,拷贝到LogicRecvBuf中。
        private static void OnReceive(object sender, SocketAsyncEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            if (e.LastOperation != SocketAsyncOperation.Receive)
            {
                return;
            }

            if (e.SocketError != SocketError.Success)
            {
                return;
            }

            OnRecvObj recvData = e.UserToken as OnRecvObj;

            if (recvData == null)
            {
                return;
            }

            if (recvData.m_RecvBuffer == null)
            {
                return;
            }

            if (recvData.m_LogicRecvHandler == null)
            {
                return;
            }

            if (recvData.m_TSocket == null)
            {
                return;
            }

            LogicRecvBufQueue logicRecvBufQueue = recvData.m_LogicRecvHandler.GetLogicRecvBufQueue();

            if (logicRecvBufQueue == null)
            {
                //-- log
                return;
            }

            LogicRecvBuffer logicRecvBuf = logicRecvBufQueue.GetEmptyBuf();

            if (logicRecvBuf == null)
            {
                //-- log
                return;
            }

            MemoryStream memStream = logicRecvBuf.GetMemoryStream();

            if (memStream == null)
            {
                //-- log
                return;
            }

            if (e.BytesTransferred > 0)
            {
                //-- test
                //Console.WriteLine("e.BytesTransferred:=[" + e.BytesTransferred + "]");

                //-- 拷贝数据要从memStream的头写入。
                memStream.Seek(0, SeekOrigin.Begin);
                memStream.Write(e.Buffer, 0, e.BytesTransferred);
                memStream.Seek(0, SeekOrigin.Begin);
                logicRecvBuf.SetUsedFlag(true);
                //-- 释放recvData.m_RecvBuffer
                recvData.m_RecvBuffer.SetUsedFlag(false);
                //-- 继续接收
                recvData.m_TSocket.RecvFromSocketBuf(recvData.m_LogicRecvHandler);
            }
            else
            {
                recvData.m_RecvBuffer.SetUsedFlag(false);
                //-- log查看是否接收缓冲区满了
                CommonDebugLog.Log("Server DisConnect!!!");
                NetClient.GetInstance().Disconnect();
            }
            return;
        }
Ejemplo n.º 16
0
        private bool Send(SocketSendBuf sendBuff)
        {
            if (sendBuff == null)
            {
                return(false);
            }

            MemoryStream sendMemStream = sendBuff.GetMemoryStream();

            if (sendMemStream == null)
            {
                return(false);
            }

            if (sendMemStream.Length == 0)
            {
                return(true);
            }

            if (sendBuff.IsFinished())
            {
                return(true);
            }

            //-- 异步将发送缓冲区数据发送出去。
            OnSendObj sendObj = new OnSendObj();

            sendObj.m_SendBuffer = sendBuff;
            sendObj.m_TSocket    = this;

            SocketAsyncEventArgs sendCompleteArgs = new SocketAsyncEventArgs();

            sendCompleteArgs.RemoteEndPoint = m_IPAndPoint;
            sendCompleteArgs.UserToken      = sendObj;
            sendCompleteArgs.Completed     += new EventHandler <SocketAsyncEventArgs>(OnSend);
            try
            {
                //-- 下面的以后放在一个pool中。
                byte[] tmpbyteArray = new byte[(int)sendMemStream.Length];
                Array.Copy(sendMemStream.GetBuffer(), tmpbyteArray, (int)sendMemStream.Length);
                sendCompleteArgs.SetBuffer(tmpbyteArray, 0, tmpbyteArray.Length);

                //sendCompleteArgs.SetBuffer(sendMemStream.GetBuffer(), sendBuff.GetTransferByteNum(), (int)sendMemStream.Length);

                //-- test log
                //Console.WriteLine("sendMemStream.Length:==[" + sendMemStream.Length + "]");
            }
            catch (System.Exception ex)
            {
                //-- log
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
                return(false);
            }

            //-: true,io pend. waiting callback
            try
            {
                if (!m_Socket.SendAsync(sendCompleteArgs))
                {
                    OnSend(null, sendCompleteArgs);
                }
            }
            catch (System.Exception ex)
            {
                CommonDebugLog.LogWarning("ex:=[" + ex.ToString() + "]");
            }


            return(true);
        }