Esempio n. 1
0
 private void SetClientState(eClientState uState)
 {
     lock (mMutex)
     {
         mState = uState;
     }
 }
Esempio n. 2
0
        void OnSocketStateEvent(eClientState status)
        {
            switch (status)
            {
            case eClientState.eClient_STATE_ABORT:
                ClearTempList();
                if (OnSocketAbort != null)
                {
                    OnSocketAbort();
                }
                break;

            case eClientState.eClient_STATE_CONNECT_FAIL:
                ClearTempList();
                if (OnConnectResult != null)
                {
                    OnConnectResult(false);
                }
                break;

            case eClientState.eClient_STATE_CONNECTED:
                SendTempList();
                if (OnConnectResult != null)
                {
                    OnConnectResult(true);
                }
                break;
            }
        }
Esempio n. 3
0
    /// <summary>
    /// 响应socket连接状态
    /// </summary>
    /// <param name="state"></param>
    private void OnSocketStateEvt(eClientState state)
    {
        switch (state)
        {
        case eClientState.eCLIENT_STATE_NONE:
            Debug.Log("None");
            break;

        case eClientState.eClient_STATE_CONNECTING:
            Debug.Log("connecting");
            break;

        case eClientState.eClient_STATE_CONNECTED:
            Debug.Log("connected");
            break;

        case eClientState.eClient_STATE_CONNECT_FAIL:
            Debug.Log("connect fail");
            break;

        case eClientState.eClient_STATE_ABORT:
            Debug.Log("abort");
            break;

        case eClientState.eClient_STATE_DISCONNECT:
            Debug.Log("disconnect");
            break;

        default:
            break;
        }
    }
Esempio n. 4
0
        private void DoSend(eClientState state)
        {
            if (state != eClientState.eClient_STATE_CONNECTED)
            {
                return;
            }

            if (m_WaitSendSize > 0)
            {
                try {
                    int nRet = m_Socket.Send(m_SendBuffer, m_WaitSendSize, SocketFlags.None);
                    if (nRet < 0)
                    {
                        CloseSocket();
                        SetClientState(eClientState.eClient_STATE_ABORT);
                    }
                    else
                    {
                        lock (m_Mutex) {
                            m_WaitSendSize -= nRet;
                            if (m_WaitSendSize > 0)
                            {
                                Buffer.BlockCopy(m_SendBuffer, nRet, m_SendBuffer, 0, m_WaitSendSize);
                            }
                        }
                    }
                }
                catch (Exception e) {
                    ProcessException(e, eClientState.eClient_STATE_ABORT);
                }
            }
        }
Esempio n. 5
0
    public void Disconnect()
    {
        clientState = eClientState.Disconnected;

        try
        {
            if (streamReader != null)
            {
                streamReader.Close();
            }
        }
        catch (Exception e)
        {
            e.ToString();
        }

        try
        {
            if (streamWriter != null)
            {
                streamWriter.Close();
            }
        }
        catch (Exception e)
        {
            e.ToString();
        }

        try
        {
            if (client != null)
            {
                client.Close();
            }
        }
        catch (Exception e)
        {
            e.ToString();
        }

        if (readThread != null)
        {
            readThread.Join(1000);

            if (readThread.ThreadState != ThreadState.Stopped)
            {
                Debug.Log("[TCPClient] Read Thread not closed. Aborting...");
                readThread.Abort();
                readThread = null;
            }
            else
            {
                readThread = null;
            }
        }
    }
Esempio n. 6
0
        private void AddConnectReq(string pRemoteIp, int uRemotePort, int mTimeOut)
        {
            tReqConnect pReq = new tReqConnect(pRemoteIp, uRemotePort, mTimeOut);

            lock (mMutex)
            {
                mState = eClientState.eClient_STATE_CONNECTING;
                LinkedListNode <tReqHead> node = new LinkedListNode <tReqHead>(pReq);
                mQueueReq.AddLast(node);
            }
        }
Esempio n. 7
0
        public bool Connect(string pRemoteIp, int uRemotePort, int mTimeOut = -1)
        {
            eClientState state = GetState();

            if ((state == eClientState.eClient_STATE_CONNECTING) || (state == eClientState.eClient_STATE_CONNECTED))
            {
                return(false);
            }

            AddConnectReq(pRemoteIp, uRemotePort, mTimeOut);
            return(true);
        }
Esempio n. 8
0
    private void ReadData()
    {
        bool endOfStream = false;

        if (!endOfStream)
        {
            if (socketType == eTCPSocketType.Text)
            {
                String response = null;

                try
                {
                    response = streamReader.ReadLine();
                }
                catch (Exception e)
                {
                    e.ToString();
                }

                if (response != null)
                {
                    response = response.Replace(Environment.NewLine, "");
                    eventQueue.Enqueue(eTCPEventType.DataReceived);
                    messageQueue.Enqueue(response);
                }
                else
                {
                    endOfStream = true;
                }
            }
            else if (socketType == eTCPSocketType.Binary)
            {
                byte[] bytes     = new byte[bufferSize];
                int    bytesRead = stream.Read(bytes, 0, bufferSize);

                if (bytesRead == 0)
                {
                    endOfStream = true;
                }
                else
                {
                    eventQueue.Enqueue(eTCPEventType.DataReceived);
                    packetsQueue.Enqueue(new SocketPacket(bytes, bytesRead));
                }
            }
        }

        clientState = eClientState.Disconnected;
        client.Close();
        eventQueue.Enqueue(eTCPEventType.Disconnected);
    }
Esempio n. 9
0
        private void Execute()
        {
            // 没有在连接状态
            try {
                // 可以考虑用ManualResetEvent而不Update
                eClientState state = GetState();
                if ((state != eClientState.eClient_STATE_CONNECTED) && (state != eClientState.eClient_STATE_CONNECTING))
                {
                    Thread.Sleep(1);
                    return;
                }

                /*
                 * 后面可以考虑发送线程和主线程两个队列,直接交换指针
                 * 性能可以更优化
                 */
                tReqHead pHead = GetFirstReq();
                if (pHead != null)
                {
                    if (pHead.uReqType == eReqType.eREQ_TYPE_CONNECT)
                    {
                        HandleConnect(pHead);
                        RemoteFirstReq();
                        pHead.Dispose();
                    }
                    else
                    {
                        if (pHead.uReqType == eReqType.eREQ_TYPE_SEND)
                        {
                            if (HandleSendReq(pHead))
                            {
                                RemoteFirstReq();
                                pHead.Dispose();
                            }
                        }
                    }
                }

                DoSend(state);
                DoRead(state);

                Thread.Sleep(1);
            }
            catch (ThreadAbortException ex) {
#if DEBUG
                // 不做处理
                UnityEngine.Debug.LogError(ex.ToString());
#endif
            }
        }
Esempio n. 10
0
        private void ProcessException(Exception e, eClientState state)
        {
            if (e == null)
            {
                return;
            }

            CloseSocket();

            if (!(e is ThreadAbortException))
            {
                SetClientState(state);
            }
        }
Esempio n. 11
0
        public bool Send(byte[] pData)
        {
            if ((pData == null) || (pData.Length <= 0))
            {
                return(false);
            }

            eClientState state = GetState();

            if (state != eClientState.eClient_STATE_CONNECTED)
            {
                return(false);
            }

            AddSendReq(pData);
            return(true);
        }
Esempio n. 12
0
    //-------------------------------------------------------------------
    public void SetState(eClientState state)
    {
        HopperUI.SetActive(false);
        JoinUI.SetActive(false);

        CurrentState = state;
        switch (state)
        {
        case eClientState.DISCOVER:
            JoinUI.SetActive(true);
            break;

        case eClientState.LOBBY:
        case eClientState.IN_GAME:
            HopperUI.SetActive(true);
            break;
        }
    }
Esempio n. 13
0
    public void Connect(string hostName, int portNumber)
    {
        if (verbose)
        {
            print("[TCPClient] Trying To Connect To: " + hostName + " " + portNumber);
        }
        if (clientState == eClientState.Connected)
        {
            return;
        }

        this.hostName = hostName;
        this.port     = portNumber;
        clientState   = eClientState.Connecting;
        messageQueue.Clear();
        eventQueue.Clear();
        client = new TcpClient();
        client.BeginConnect(hostName, port, new AsyncCallback(ConnectCallback), client);
    }
Esempio n. 14
0
 private void SetTcpClient(TcpClient tcpClient)
 {
     client = tcpClient;
     if (client.Connected)
     {
         stream       = client.GetStream();
         streamReader = new StreamReader(stream);
         streamWriter = new StreamWriter(stream);
         clientState  = eClientState.Connected;
         eventQueue.Enqueue(eTCPEventType.Connected);
         readThread = new Thread(ReadData);
         readThread.IsBackground = true;
         readThread.Start();
     }
     else
     {
         clientState = eClientState.Disconnected;
     }
 }
Esempio n. 15
0
        private void DoRead(eClientState state)
        {
            if (state != eClientState.eClient_STATE_CONNECTED)
            {
                return;
            }

            try {
                // 读取数据
                if (m_Socket.Poll(0, SelectMode.SelectRead))
                {
                    int readSize = m_ReadBuffer.Length - m_HasReadSize;
                    if (readSize > 0)
                    {
                        int nRet = m_Socket.Receive(m_ReadBuffer, m_HasReadSize, readSize, SocketFlags.None);
                        if (nRet <= 0)
                        {
                            CloseSocket();
                            //m_State = eClientState.eClient_STATE_ABORT;
                            SetClientState(eClientState.eClient_STATE_ABORT);
                        }
                        else
                        {
                            m_HasReadSize += nRet;
                            // BUFFER的线程方法
                            if (OnThreadBufferProcess != null)
                            {
                                OnThreadBufferProcess(this);
                            }
                            else
                            {
                                m_HasReadSize = 0;
                            }
                        }
                    }
                }
            }
            catch (Exception e) {
                ProcessException(e, eClientState.eClient_STATE_ABORT);
            }
        }
Esempio n. 16
0
        public bool Send(byte[] pData, int bufSize = -1)
        {
            if ((pData == null) || (pData.Length <= 0))
            {
                return(false);
            }

            eClientState state = GetState();

            if (state != eClientState.eClient_STATE_CONNECTED)
            {
                return(false);
            }

            if (bufSize < 0)
            {
                bufSize = pData.Length;
            }
            AddSendReq(pData, bufSize);
            return(true);
        }
Esempio n. 17
0
        // 声明为同步函数
        //[MethodImplAttribute(MethodImplOptions.Synchronized)]
        public bool Execute()
        {
            //	string threadId = Thread.CurrentThread.ManagedThreadId.ToString ();
            //	Console.WriteLine (threadId);

            if (mTcpClient == null)
            {
                Stop();
                return(false);
            }

            if (mConnecting)
            {
                eClientState state = mTcpClient.GetState();
                if ((state == eClientState.eClient_STATE_CONNECTING) ||
                    (state == eClientState.eCLIENT_STATE_NONE))
                {
                    return(true);
                }

                if ((state == eClientState.eClient_STATE_CONNECT_FAIL) ||
                    (state == eClientState.eClient_STATE_ABORT))
                {
                    mConnecting = false;
                    mAbort      = false;
                    mTcpClient.Release();
                    mTcpClient = null;
                    OnClearData();

                    // Call Event Error
                    if (mStateEvents != null)
                    {
                        mStateEvents(state);
                    }

                    return(false);
                }
                else if (state == eClientState.eClient_STATE_CONNECTED)
                {
                    mConnecting = false;
                    mAbort      = false;

                    // Call Event Success
                    if (mStateEvents != null)
                    {
                        mStateEvents(state);
                    }

                    return(true);
                }

                mConnecting = false;
            }

            ProcessPackets();

            if (mTcpClient != null && !mTcpClient.HasReadData())
            {
                if (!mAbort)
                {
                    eClientState state = mTcpClient.GetState();
                    if (state == eClientState.eClient_STATE_ABORT)
                    {
                        mAbort = true;
                        OnClearData();
                        // Call Event Abort
                        if (mStateEvents != null)
                        {
                            mStateEvents(state);
                        }

                        return(false);
                    }
                }
            }
            return(true);
        }
Esempio n. 18
0
        public bool Execute_QiPai()
        {
            if (mTcpClient == null)
            {
                canUpdate = false;
                return(false);
            }

            if (mConnecting)
            {
                eClientState state = mTcpClient.GetState();
                if ((state == eClientState.eClient_STATE_CONNECTING) ||
                    (state == eClientState.eCLIENT_STATE_NONE))
                {
                    return(true);
                }

                if ((state == eClientState.eClient_STATE_CONNECT_FAIL) ||
                    (state == eClientState.eClient_STATE_ABORT))
                {
                    mConnecting = false;
                    mAbort      = false;
                    mTcpClient.Release();
                    mTcpClient = null;

                    // Call Event Error
                    if (mStateEvents != null)
                    {
                        mStateEvents(state);
                    }

                    return(false);
                }
                else if (state == eClientState.eClient_STATE_CONNECTED)
                {
                    mConnecting = false;
                    mAbort      = false;

                    // Call Event Success
                    if (mStateEvents != null)
                    {
                        mStateEvents(state);
                    }

                    return(true);
                }

                mConnecting = false;
            }

            if (mTcpClient.HasReadData())
            {
                int recvsize = mTcpClient.GetReadData(mRecvBuffer, mRecvSize);
                if (recvsize > 0)
                {
                    mRecvSize += recvsize;
                    int recvBufSz = mRecvSize;
                    int i         = 0;
                    GamePackHeader_QiPai header = new GamePackHeader_QiPai();
                    int    headerSize           = Marshal.SizeOf(header);
                    IntPtr headerBuffer         = Marshal.AllocHGlobal(headerSize);
                    try
                    {
                        //可能粘包,用循环来切包
                        while (recvBufSz - i >= headerSize)
                        {
                            Marshal.Copy(mRecvBuffer, i, headerBuffer, headerSize);
                            header = (GamePackHeader_QiPai)Marshal.PtrToStructure(headerBuffer, typeof(GamePackHeader_QiPai));
                            string descStr = System.Text.Encoding.Default.GetString(header.desc);

                            if (descStr == "GTV1")
                            {
                            }

                            int msgId     = (header.msgId[0] << 8) + header.msgId[1];
                            int msgLength = (header.msgLength[0] << 8) + header.msgLength[1];

                            //断包,break掉,继续接收
                            if ((recvBufSz - i) < (msgLength + headerSize))
                            {
                                break;
                            }

                            byte[] dataBytes = new byte[msgLength];
                            Buffer.BlockCopy(mRecvBuffer, i + headerSize, dataBytes, 0, msgLength);

                            dataBytes = codeData(dataBytes);

                            GamePacket packet = new GamePacket();
                            packet.header = header;
                            packet.data   = dataBytes;

                            LinkedListNode <GamePacket> node = new LinkedListNode <GamePacket>(packet);
                            mPacketList.AddLast(node);

                            i += headerSize + msgLength;//当前包已处理完,偏移量移动,开始处理下一个包
                        }
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(headerBuffer);
                    }

                    recvBufSz -= i;
                    mRecvSize  = recvBufSz;
                    if (recvBufSz > 0)
                    {
                        Buffer.BlockCopy(mRecvBuffer, i, mRecvBuffer, 0, recvBufSz); //剩余的数据往前移
                    }
                    ProcessPackets();
                    return(true);
                }
            }
            else
            {
                if (!mAbort)
                {
                    eClientState state = mTcpClient.GetState();
                    if (state == eClientState.eClient_STATE_ABORT)
                    {
                        mAbort = true;

                        // Call Event Abort
                        if (mStateEvents != null)
                        {
                            mStateEvents(state);
                        }

                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 19
0
        /// <summary>
        /// Quits a client from the world
        /// </summary>
        protected internal void Quit()
        {
            lock (this)
            {
                try
                {
                    eClientState oldClientState = ClientState;
                    if (m_sessionID != 0)
                    {
                        if (oldClientState == eClientState.Playing || oldClientState == eClientState.WorldEnter ||
                            oldClientState == eClientState.Linkdead)
                        {
                            try
                            {
                                if (Player != null)
                                {
                                    Player.Quit(true);                                     //calls delete
                                }
                                //m_player.Delete(true);
                            }
                            catch (Exception e)
                            {
                                log.Error("player cleanup on client quit", e);
                            }
                        }

                        try
                        {
                            //Now free our objid and sessionid again
                            WorldMgr.RemoveClient(this);                             //calls RemoveSessionID -> player.Delete
                        }
                        catch (Exception e)
                        {
                            log.Error("client cleanup on quit", e);
                        }
                    }

                    ClientState = eClientState.Disconnected;
                    Player      = null;

                    GameEventMgr.Notify(GameClientEvent.Disconnected, this);

                    if (Account != null)
                    {
                        if (log.IsInfoEnabled)
                        {
                            if (m_udpEndpoint != null)
                            {
                                log.Info("(" + m_udpEndpoint.Address + ") " + Account.Name + " just disconnected!");
                            }
                            else
                            {
                                log.Info("(" + TcpEndpoint + ") " + Account.Name + " just disconnected!");
                            }
                        }

                        // log disconnect
                        AuditMgr.AddAuditEntry(this, AuditType.Account, AuditSubtype.AccountLogout, "", Account.Name);
                    }
                }
                catch (Exception e)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("Quit", e);
                    }
                }
            }
        }
Esempio n. 20
0
        public bool Execute()
        {
            //	string threadId = Thread.CurrentThread.ManagedThreadId.ToString ();
            //	Console.WriteLine (threadId);

            if (mTcpClient == null)
            {
                Stop();
                return(false);
            }

            if (mConnecting)
            {
                eClientState state = mTcpClient.GetState();
                if ((state == eClientState.eClient_STATE_CONNECTING) ||
                    (state == eClientState.eCLIENT_STATE_NONE))
                {
                    return(true);
                }

                if ((state == eClientState.eClient_STATE_CONNECT_FAIL) ||
                    (state == eClientState.eClient_STATE_ABORT))
                {
                    mConnecting = false;
                    mAbort      = false;
                    mTcpClient.Release();
                    mTcpClient = null;

                    // Call Event Error
                    if (mStateEvents != null)
                    {
                        mStateEvents(state);
                    }

                    return(false);
                }
                else if (state == eClientState.eClient_STATE_CONNECTED)
                {
                    mConnecting = false;
                    mAbort      = false;

                    // Call Event Success
                    if (mStateEvents != null)
                    {
                        mStateEvents(state);
                    }

                    return(true);
                }

                mConnecting = false;
            }

            if (mTcpClient.HasReadData())
            {
                int recvsize = mTcpClient.GetReadData(mRecvBuffer, mRecvSize);
                if (recvsize > 0)
                {
                    mRecvSize += recvsize;
                    int            recvBufSz = mRecvSize;
                    int            i         = 0;
                    GamePackHeader header    = new GamePackHeader();

                    int    headerSize   = Marshal.SizeOf(header);
                    IntPtr headerBuffer = Marshal.AllocHGlobal(headerSize);
                    try {
                        while (recvBufSz - i >= headerSize)
                        {
                            Marshal.Copy(mRecvBuffer, i, headerBuffer, headerSize);
                            header = (GamePackHeader)Marshal.PtrToStructure(headerBuffer, typeof(GamePackHeader));
#if USE_NETORDER
                            // used Net
                            header.headerCrc32 = (uint)IPAddress.NetworkToHostOrder(header.headerCrc32);
                            header.dataCrc32   = (uint)IPAddress.NetworkToHostOrder(header.dataCrc32);
                            header.header      = IPAddress.NetworkToHostOrder(header.header);
                            header.dataSize    = IPAddress.NetworkToHostOrder(header.dataSize);
#endif
                            if ((recvBufSz - i) < (header.dataSize + headerSize))
                            {
                                break;
                            }
                            GamePacket packet = new GamePacket();
                            packet.header = header;
                            if (packet.header.dataSize <= 0)
                            {
                                packet.header.dataSize = 0;
                                packet.data            = null;
                            }
                            else
                            {
                                packet.data = new byte[packet.header.dataSize];
                                Buffer.BlockCopy(mRecvBuffer, i + headerSize, packet.data, 0, packet.header.dataSize);
                            }

                            LinkedListNode <GamePacket> node = new LinkedListNode <GamePacket>(packet);
                            mPacketList.AddLast(node);

                            i += headerSize + header.dataSize;
                        }
                    } finally {
                        Marshal.FreeHGlobal(headerBuffer);
                    }

                    recvBufSz -= i;
                    mRecvSize  = recvBufSz;
                    if (recvBufSz > 0)
                    {
                        Buffer.BlockCopy(mRecvBuffer, i, mRecvBuffer, 0, recvBufSz);
                    }

                    ProcessPackets();
                    return(true);
                }
            }
            else
            {
                if (!mAbort)
                {
                    eClientState state = mTcpClient.GetState();
                    if (state == eClientState.eClient_STATE_ABORT)
                    {
                        mAbort = true;

                        // Call Event Abort
                        if (mStateEvents != null)
                        {
                            mStateEvents(state);
                        }

                        return(false);
                    }
                }
            }

            return(true);
        }