Пример #1
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            AsyncSocketUserToken userToken = asyncSocketUserTokenPool.Pop();

            asyncSocketUserTokenList.Add(userToken); //添加到正在连接列表
            userToken.ConnectSocket   = acceptEventArgs.AcceptSocket;
            userToken.ConnectDateTime = DateTime.Now;
            userToken.serverSocket    = this;
            Tools.MyLog.Log("New client {0} accept, Client count {1}", acceptEventArgs.AcceptSocket.RemoteEndPoint, asyncSocketUserTokenList.Count);

            try
            {
                bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                if (!willRaiseEvent)
                {
                    lock (userToken)
                    {
                        ProcessReceive(userToken.ReceiveEventArgs);
                    }
                }
            }
            catch (Exception e)
            {
                Tools.MyLog.Error("Accept client {0} error, \nmessage: {1} \nstackTrace: {2}", userToken.ConnectSocket, e.Message, e.StackTrace);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
Пример #2
0
        private void CloseClientSocket(AsyncSocketUserToken userToken)
        {
            if (userToken.ConnectSocket == null)
            {
                return;
            }

            string socketInfo = string.Format("Remote Address: {0}", userToken.ConnectSocket.RemoteEndPoint);

            socketInfo = string.Format("Client disconnected {0}.", socketInfo);

            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                Tools.MyLog.Error("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message);
            }

            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源

            maxNumberAcceptedClients.Release();
            asyncSocketUserTokenPool.Push(userToken);
            asyncSocketUserTokenList.Remove(userToken);

            MyLog.Log("{0} Client count {1}", socketInfo, asyncSocketUserTokenList.Count);
        }
Пример #3
0
        private void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs)
        {
            AsyncSocketUserToken userToken = asyncEventArgs.UserToken as AsyncSocketUserToken;

            userToken.ActiveTime = 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)
            {
                Tools.MyLog.Error("IO_Completed {0} error, \nmessage: {1} \nstackTrace: {2}", userToken.ConnectSocket, e.Message, e.StackTrace);
            }
        }
Пример #4
0
 public void Remove(AsyncSocketUserToken userToken)
 {
     lock (list)
     {
         list.Remove(userToken);
     }
 }
Пример #5
0
 public void Add(AsyncSocketUserToken userToken)
 {
     lock (list)
     {
         list.Add(userToken);
     }
 }
Пример #6
0
 public void CopyList(ref AsyncSocketUserToken[] array)
 {
     lock (list)
     {
         array = new AsyncSocketUserToken[list.Count];
         list.CopyTo(array);
     }
 }
Пример #7
0
 public void Push(AsyncSocketUserToken item)
 {
     if (item == null)
     {
         throw new ArgumentException("Items added to a AsyncSocketUserToken cannot be null");
     }
     lock (pool)
     {
         pool.Push(item);
     }
 }
Пример #8
0
        private bool ProcessSend(SocketAsyncEventArgs sendEventArgs)
        {
            AsyncSocketUserToken userToken = sendEventArgs.UserToken as AsyncSocketUserToken;

            userToken.ActiveTime = DateTime.Now;
            if (sendEventArgs.SocketError == SocketError.Success)
            {
                return(userToken.SendCompleted()); //调用子类回调函数
            }
            else
            {
                CloseClientSocket(userToken);
                return(false);
            }
        }
Пример #9
0
        private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs)
        {
            AsyncSocketUserToken userToken = receiveEventArgs.UserToken as AsyncSocketUserToken;

            if (userToken.ConnectSocket == null)
            {
                return;
            }
            userToken.ActiveTime = DateTime.Now;
            if (userToken.ReceiveEventArgs.BytesTransferred > 0 && userToken.ReceiveEventArgs.SocketError == SocketError.Success)
            {
                int offset = userToken.ReceiveEventArgs.Offset;
                int count  = userToken.ReceiveEventArgs.BytesTransferred;

                if (count > 0) //处理接收数据
                {
                    //如果处理数据返回失败,则断开连接
                    if (!userToken.ProcessReceive(userToken.ReceiveEventArgs.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);
            }
        }
Пример #10
0
        public Server(int _port)
        {
            port = _port;

            maxNumberAcceptedClients = new Semaphore(Config.PARALLE_NUM, Config.PARALLE_NUM);
            asyncSocketUserTokenList = new AsyncSocketUserTokenList();
            asyncSocketUserTokenPool = new AsyncSocketUserTokenPool(Config.PARALLE_NUM);

            // 按照连接数建立读写对象
            AsyncSocketUserToken userToken;

            for (int i = 0; i < Config.PARALLE_NUM; i++)
            {
                userToken = new AsyncSocketUserToken();
                userToken.ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                userToken.SendEventArgs.Completed    += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                asyncSocketUserTokenPool.Push(userToken);
            }
        }