/// <summary>
        /// 客户端关闭连接释放
        /// </summary>
        /// <param name="userToken"></param>
        public void CloseClientSocket(AsyncSocketUserToken userToken)
        {
            if (userToken.ConnectSocket == null)
            {
                return;
            }
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                                              userToken.ConnectSocket.RemoteEndPoint);

            SignOutAction?.Invoke(userToken.ConnectSocket.RemoteEndPoint.ToString(), userToken.Flag);
            // LogService.Instance.InfoFormatted("Client connection disconnected. {0}", socketInfo);
            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                // LogService.Instance.ErrorFormatted("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message);
            }
            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源

            m_maxNumberAcceptedClients.Release();
            m_asyncSocketUserTokenPool.Push(userToken);
            m_asyncSocketUserTokenList.Remove(userToken);
        }
        //收发消息
        void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs)
        {
            AsyncSocketUserToken userToken = asyncEventArgs.UserToken as AsyncSocketUserToken;

            userToken.ActiveDateTime = DateTime.Now;
            try
            {
                lock (userToken)
                {
                    if (asyncEventArgs.LastOperation == SocketAsyncOperation.Receive)
                    {
                        ProcessReceive(asyncEventArgs);
                    }
                    else if (asyncEventArgs.LastOperation == SocketAsyncOperation.Send)
                    {
                        ProcessSend(asyncEventArgs);
                    }
                    else
                    {
                        throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                    }
                }
            }
            catch (Exception E)
            {
                // LogService.Instance.ErrorFormatted("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                // LogService.Instance.Error(E.StackTrace);
            }
        }
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            // LogService.Instance.InfoFormatted("Client connection accepted. Local Address: {0}, Remote Address: {1}",
            //      acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);

            AsyncSocketUserToken userToken = m_asyncSocketUserTokenPool.Pop();

            m_asyncSocketUserTokenList.Add(userToken); //添加到正在连接列表
            userToken.ConnectSocket   = acceptEventArgs.AcceptSocket;
            userToken.ConnectDateTime = DateTime.Now;

            try
            {
                bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                if (!willRaiseEvent)
                {
                    lock (userToken)
                    {
                        ProcessReceive(userToken.ReceiveEventArgs);
                    }
                }
            }
            catch (Exception E)
            {
                // LogService.Instance.ErrorFormatted("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                // LogService.Instance.Error(E.StackTrace);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
Example #4
0
 public void Remove(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Remove(userToken);
     }
 }
Example #5
0
 public void Add(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Add(userToken);
     }
 }
        /// <summary>
        /// 数据接收处理分发
        /// </summary>
        /// <param name="receiveEventArgs"></param>
        private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs)
        {
            AsyncSocketUserToken userToken = receiveEventArgs.UserToken as AsyncSocketUserToken;

            if (userToken.ConnectSocket == null)
            {
                return;
            }
            userToken.ActiveDateTime = DateTime.Now;
            if (userToken.ReceiveEventArgs.BytesTransferred > 0 && userToken.ReceiveEventArgs.SocketError == SocketError.Success)
            {
                int offset = userToken.ReceiveEventArgs.Offset;
                int count  = userToken.ReceiveEventArgs.BytesTransferred;
                if ((userToken.AsyncSocketInvokeElement == null) & (userToken.ConnectSocket != null)) //存在Socket对象,并且没有绑定协议对象,则进行协议对象绑定
                {
                    BuildingSocketInvokeElement(userToken);                                           ///添加的解析类
                    //  offset = offset + 1;
                    // count = count - 1;
                }
                if (userToken.AsyncSocketInvokeElement == null) //如果没有解析对象,提示非法连接并关闭连接
                {
                    CloseClientSocket(userToken);
                    // LogService.Instance.WarnFormatted("Illegal client connection. Local Address: {0}, Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                    //    userToken.ConnectSocket.RemoteEndPoint);
                }
                else
                {
                    if (count > 0) //处理接收数据
                    {
                        byte[] buffer = new byte[count];
                        Array.Copy(userToken.ReceiveEventArgs.Buffer, 0, buffer, 0, count);
                        if (!userToken.AsyncSocketInvokeElement.ProcessReceive(buffer, offset, count))
                        { //如果处理数据返回失败,则断开连接
                            CloseClientSocket(userToken);
                        }
                        else //否则投递下次介绍数据请求
                        {
                            bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                            if (!willRaiseEvent)
                            {
                                ProcessReceive(userToken.ReceiveEventArgs);
                            }
                        }
                    }
                    else
                    {
                        bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                        if (!willRaiseEvent)
                        {
                            ProcessReceive(userToken.ReceiveEventArgs);
                        }
                    }
                }
            }
            else
            {
                CloseClientSocket(userToken);
            }
        }
Example #7
0
 public void Push(AsyncSocketUserToken item)
 {
     if (item == null)
     {
         throw new ArgumentException("Items added to a AsyncSocketUserToken cannot be null");
     }
     lock (m_pool)
     {
         m_pool.Push(item);
     }
 }
        /// <summary>
        /// 解析协议 指定消息解析方式
        /// </summary>
        /// <param name="userToken"></param>
        private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken)
        {
            //byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset];
            //userToken.AsyncSocketInvokeElement = new BaseSocketProtocol(this, userToken);

            BuildingSocketProtocol?.Invoke(this, userToken);
            if (userToken.AsyncSocketInvokeElement != null)
            {
                // LogService.Instance.InfoFormatted("Building socket invoke element {0}.Local Address: {1}, Remote Address: {2}",
                //    userToken.AsyncSocketInvokeElement, userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint);
            }
        }
        /// <summary>
        /// 创建连接缓存
        /// </summary>
        /// <param name="receiveBufferSize">缓存字节数组的长度</param>
        public void Init(int receiveBufferSize)
        {
            AsyncSocketUserToken userToken;

            for (int i = 0; i < NnumConnections; i++) //按照连接数建立读写对象
            {
                userToken = new AsyncSocketUserToken(receiveBufferSize);
                userToken.ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                userToken.SendEventArgs.Completed    += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                m_asyncSocketUserTokenPool.Push(userToken);
            }
        }
        public AsyncSocketInvokeElement(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
        {
            m_asyncSocketServer    = asyncSocketServer;
            m_asyncSocketUserToken = asyncSocketUserToken;

            m_netByteOrder = false;


            m_sendAsync = false;

            m_connectDT = DateTime.UtcNow;
            m_activeDT  = DateTime.UtcNow;
        }
        private bool ProcessSend(SocketAsyncEventArgs sendEventArgs)
        {
            AsyncSocketUserToken userToken = sendEventArgs.UserToken as AsyncSocketUserToken;

            if (userToken.AsyncSocketInvokeElement == null)
            {
                return(false);
            }
            userToken.ActiveDateTime = DateTime.Now;
            if (sendEventArgs.SocketError == SocketError.Success)
            {
                return(userToken.AsyncSocketInvokeElement.SendCompleted()); //调用子类回调函数
            }
            else
            {
                CloseClientSocket(userToken);
                return(false);
            }
        }
Example #12
0
 public BaseSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "";
 }