Exemple #1
0
 /// <summary>
 /// CallBack After Socket Connectd
 /// </summary>
 /// <param name="ar"></param>
 private void ConnectCallback(IAsyncResult ar)
 {
     try
     {
         ar.AsyncWaitHandle.Close();
         if (m_Socket != null)
         {
             m_Socket.EndConnect(ar);
             m_Socket.Blocking       = false;               // 非阻断
             m_Socket.ReceiveTimeout = 3000;
             m_Socket.SendTimeout    = 3000;
         }
         m_State = TNetState.State_Connected;
         if (m_HandleOnConnected != null)
         {
             m_HandleOnConnected(0);
         }
     }
     catch (Exception ex)
     {
         if (m_HandleOnConnected != null)
         {
             m_HandleOnConnected(-1);
         }
         BTDebug.Exception("Socket Connect CallBack Exception:" + ex.Message);
         Disconnect(TNetState.State_ConnectFailed);
     }
 }
Exemple #2
0
        public bool Connect(string remote, int port)
        {
            try
            {
                m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_clientSocket.Connect(remote, port);
                if (m_clientSocket.Connected)
                {
                    m_clientSocket.Blocking       = false;
                    m_clientSocket.ReceiveTimeout = 0;
                    m_clientSocket.SendTimeout    = 0;
                    Sys_Log("OKKK");
                    m_state        = TNetState.NET_STATE_CONNECTING;
                    m_connTime     = Sys_GetTime();
                    m_lastSendTime = Sys_GetTime();
                    m_lastRecvTime = Sys_GetTime();

                    Thread newthread = new Thread(new ThreadStart(ListenThread));
                    newthread.Start();
                    return(true);
                }
            }
            catch (System.Exception ex)
            {
                Sys_Log(ex.Message);
            }
            return(false);
        }
Exemple #3
0
 /// <summary>
 /// 断开连接
 /// </summary>
 /// <param name="state"></param>
 /// <returns></returns>
 public Int32 Disconnect(TNetState state)
 {
     BTDebug.Log("Disconnect For:" + state.ToString(), "NET");
     m_State = state;
     if (m_Socket == null)
     {
         return(0);
     }
     try
     {
         if (m_Socket.Connected == true)
         {
             m_Socket.Shutdown(SocketShutdown.Both);
             if (m_HandleOnDisConnected != null)
             {
                 m_HandleOnDisConnected(0);
             }
         }
     }
     catch (System.Exception ex)
     {
         BTDebug.Exception("ShutDown Socket Error:" + ex.Message);
         if (m_HandleOnDisConnected != null)
         {
             m_HandleOnDisConnected(-1);
         }
     }
     m_Socket.Close();
     m_Socket = null;
     return(0);
 }
Exemple #4
0
 void FlushData()
 {
     lock (m_writeBuf)
     {
         if (m_state == TNetState.NET_STATE_DEAD)
         {
             return;
         }
         if (m_writeBuf.Count == 0)
         {
             return;
         }
         int ret = m_clientSocket.Send(m_writeBuf.ToArray());
         if (ret < 0)
         {
             m_state = TNetState.NET_STATE_DEAD;
         }
         else if (ret == 0)
         {
         }
         else if (ret > 0)
         {
             m_lastSendTime = Sys_GetTime();
             m_writeBuf.RemoveRange(0, ret);
         }
     }
 }
Exemple #5
0
        bool RecvPacket(NetPacket packet)
        {
            int ret;

            ret = packet.BeginRead(m_readBuff);
            if (ret > 0)
            {
                m_readBuff.RemoveRange(0, ret);
                if (packet.IsEncrypt())
                {
                    packet.Decrypt(m_seed, m_seedLen);
                }
                if (packet.IsCompress())
                {
                    if (!packet.Uncompress())
                    {
                        return(false);
                    }
                }
                return(true);
            }
            else if (ret == 0)
            {
                return(false);
            }
            else
            {
                Sys_Log("error getcmd = -1");
                /* the packet flag error,not belong to this session */
                m_state = TNetState.NET_STATE_DEAD;
                return(false);
            }
        }
Exemple #6
0
 /// <summary>
 /// Construct
 /// </summary>
 public CSocketConnect()
 {
     m_Socket                 = null;
     m_State                  = TNetState.NS_Null;
     m_QueMsgReceive          = new SafeQueue(CNetStaticConfig.cnNetReceiveQueueSize);
     m_ReceiveByteBuff        = new Byte[CNetStaticConfig.cnNetReceiveMsgByteSize];
     m_nReceiveBuffPos        = 0;
     m_nReceiveBuffReadLength = CNetStaticConfig.cnNetReceiveMsgByteSize;
     InitReceiveThread();
 }
Exemple #7
0
 void Reset()
 {
     m_rtt = 0;
     m_readBuff.Clear();
     m_writeBuf.Clear();
     m_clientSocket.Close();
     m_clientSocket = null;
     m_seedLen      = 0;
     m_seq          = 0;
     m_state        = TNetState.NET_STATE_ZERO;
 }
Exemple #8
0
        void Process()
        {
            DefProc();
            switch (m_state)
            {
            case TNetState.NET_STATE_CONNECTED:
                while (GetPacket(m_recvCmdPkt))
                {
                    OnReceive(m_recvCmdPkt);
                }
                break;

            case TNetState.NET_STATE_DEAD:
                OnDisconnect();
                Close();
                break;

            case TNetState.NET_STATE_WAITING_SEED:
                /* try get encrypt seed */
                if (RecvPacket(m_recvNetPkt))
                {
                    m_recvNetPkt.AttachCmdPacket(m_recvCmdPkt);
                    if (m_recvNetPkt.IsSysPacket())
                    {
                        HandleSysPacket(m_recvCmdPkt);
                    }
                }
                break;

            case TNetState.NET_STATE_CONNECTING:
                if (HasExcept() ||
                    Sys_GetTime() - m_connTime > NET_CONNECT_TIMEOUT)
                {
                    Sys_Log("connecting timeout");
                    Close();
                    OnConnect(false);
                    m_state = TNetState.NET_STATE_DEAD;
                    break;
                }
                if (CanWrite())
                {
                    m_state        = TNetState.NET_STATE_WAITING_SEED;
                    m_startTime    = Sys_GetTime();
                    m_lastSendTime = m_startTime;
                    m_lastRecvTime = m_startTime;
                }
                break;
            }
        }
Exemple #9
0
        int HandleSysPacket(CmdPacket packet)
        {
            short type  = 0;
            uint  param = 0;

            if (!packet.ReadShort(ref type))
            {
                return(0);
            }
            switch (type)
            {
            case SYS_PACKET_KEEP_ALIVE:
                if (!packet.ReadUInt(ref param))
                {
                    return(0);
                }
                Sys_Log("recv keep alive msg");
                m_sendCmdPkt.BeginWrite();
                m_sendCmdPkt.WriteShort(SYS_PACKET_ALIVE_ACK);
                m_sendCmdPkt.WriteInt((int)param);
                SendPacket(m_sendCmdPkt, true, true);
                break;

            case SYS_PACKET_ALIVE_ACK:
                if (!packet.ReadUInt(ref param))
                {
                    return(0);
                }
                Sys_Log("recv alive ack msg");
                m_rtt = Sys_GetTime() - param;
                break;

            case SYS_PACKET_SET_SEED:
                if (!packet.ReadUInt(ref param))
                {
                    return(0);
                }
                SetSeed(param);
                m_state = TNetState.NET_STATE_CONNECTED;
                OnConnect(true);
                break;

            default:
                return(0);
            }
            return(type);
        }
Exemple #10
0
        /// <summary>
        /// 连接一个远程主机
        /// </summary>
        /// <param name="connectPoint"></param>
        /// <returns></returns>
        public bool ConnectHost(IPAddress connectPoint, Int32 nPort)
        {
            try
            {
                if (m_State == TNetState.State_TryConnecting)
                {
                    // connect waiting
                    return(false);
                }
                if (m_State == TNetState.State_Initialized)
                {
                    // initialized
                    return(false);
                }
                if (m_State == TNetState.State_Connected)
                {
                    // connected, do not connect again
                    return(false);
                }

                m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (m_Socket == null)
                {
                    m_State = TNetState.NS_Null;
                    return(false);
                }
                m_State = TNetState.State_Initialized;

                m_Socket.BeginConnect(connectPoint, nPort, new AsyncCallback(ConnectCallback), m_Socket);
                m_State = TNetState.State_TryConnecting;

                return(true);
            }
            catch (Exception)
            {
                Disconnect(TNetState.State_ConnectFailed);
                return(false);
            }
        }
Exemple #11
0
 bool ReadData()
 {
     if (m_state == TNetState.NET_STATE_DEAD)
     {
         return(false);
     }
     if (!CanRead())
     {
         return(false);
     }
     byte[] bytes = new byte[NetPacket.MAX_BUFFER_SIZE];
     try
     {
         int ret = m_clientSocket.Receive(bytes);
         if (ret > 0)
         {
             byte[] bytes2 = new byte[ret];
             Array.Copy(bytes, bytes2, ret);
             m_readBuff.AddRange(bytes2);
             m_lastRecvTime = Sys_GetTime();
             return(true);
         }
         else if (ret == 0)
         {
             return(false);
         }
         else
         {
             m_state = TNetState.NET_STATE_DEAD;
         }
     }
     catch (System.Exception ex)
     {
         m_state = TNetState.NET_STATE_DEAD;
         Sys_Log(ex.Message);
     }
     return(false);
 }
Exemple #12
0
 void DefProc()
 {
     if (m_state != TNetState.NET_STATE_CONNECTED && m_state != TNetState.NET_STATE_WAITING_SEED)
     {
         return;
     }
     if (m_state == TNetState.NET_STATE_CONNECTED)
     {
         uint now = Sys_GetTime();
         if (now - m_lastSendTime > NET_KEEP_ALIVE_INTERVAL)
         {
             KeepAlive(now);
             m_lastSendTime = now;
         }
         if (now - m_lastRecvTime > NET_TIMEOUT)
         {
             Sys_Log("tcp session dead reason = timeout");
             m_state = TNetState.NET_STATE_DEAD;
         }
         FlushData();
     }
     ReadData();
 }