예제 #1
0
        public void CloseClientSocketEx(AsyncSocketUserToken userToken)
        {
            if (userToken == null || userToken.ConnectSocket == null)
            {
                return;
            }
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                                              userToken.ConnectSocket.RemoteEndPoint);

            Logger.Instance().InfoFormat("CloseClientSocketEx()->Client connection disconnected. {0}", socketInfo);
            try
            {
                if (userToken.ConnectSocket != null)
                {
                    userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
                }
            }
            catch (Exception e)
            {
                Logger.Instance().ErrorFormat("CloseClientSocketEx()->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);
            userToken = null;
        }
예제 #2
0
 public BaseSocketProtocol(AsyncServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_userName   = "";
     m_logined    = false;
     m_socketFlag = "";
 }
예제 #3
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)
            {
                Global.Logger.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);

            Global.Logger.Debug("{0} Client count {1}", socketInfo, asyncSocketUserTokenList.Count);
        }
예제 #4
0
 public void Add(AsyncSocketUserToken userToken)
 {
     lock (list)
     {
         list.Add(userToken);
     }
 }
예제 #5
0
        /// <summary>
        /// IO事件完成,包括远程SOCKET断开,数据到达
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="asyncEventArgs"></param>
        private void OnIOCompleted(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)
            {
                Logger.Instance().ErrorFormat("OnIOCompleted {0} error, message: {1}", userToken.ConnectSocket, e.Message);
                Logger.Instance().Error(e.StackTrace);
            }
        }
예제 #6
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            AsyncSocketUserToken userToken = asyncSocketUserTokenPool.Pop();

            asyncSocketUserTokenList.Add(userToken); //添加到正在连接列表
            userToken.ConnectSocket   = acceptEventArgs.AcceptSocket;
            userToken.ConnectDateTime = DateTime.Now;
            userToken.serverSocket    = this;
            Global.Logger.Debug("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)
            {
                Global.Logger.Error("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                Global.Logger.Error(E.StackTrace);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
예제 #7
0
 public void Remove(AsyncSocketUserToken userToken)
 {
     lock (list)
     {
         list.Remove(userToken);
     }
 }
예제 #8
0
 public void CopyList(ref AsyncSocketUserToken[] array)
 {
     lock (list)
     {
         array = new AsyncSocketUserToken[list.Count];
         list.CopyTo(array);
     }
 }
예제 #9
0
        /// <summary>
        /// 关闭单个客户端
        /// </summary>
        /// <param name="userToken"></param>
        public void CloseClientSocket(AsyncSocketUserToken userToken)
        {
            if (userToken == null || userToken.ConnectSocket == null)
            {
                return;
            }
            if (AntiMappingIP != null)
            {
                AntiMappingIP(this, new DataTransmissionEventArgs(userToken));
            }
            if (RemoveCommandQueue != null)
            {
                RemoveCommandQueue(this, new DataTransmissionEventArgs(userToken));
            }
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                                              userToken.ConnectSocket.RemoteEndPoint);

            Logger.Instance().InfoFormat("Client connection disconnected. {0}", socketInfo);
            try
            {
                if (userToken.ConnectSocket != null)
                {
                    userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
                }
            }
            catch (Exception e)
            {
                Logger.Instance().ErrorFormat("CloseClientSocket()-> Disconnect client {0} error, message: {1}", socketInfo, e.Message);
            }
            try
            {
                if (userToken.ConnectSocket != null)
                {
                    userToken.ConnectSocket.Close();
                    userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源
                }
            }
            catch
            {
                Logger.Instance().Error("CloseClientSocket()-> userToken.ConnectSocket.Close() 出错");
            }
            m_MaxNumberAcceptedClients.Release();
            if (userToken != null)
            {
                m_AsyncSocketUserTokenPool.Push(userToken);
                m_AsyncSocketUserTokenList.Remove(userToken);
            }

            ///当最后一个连接被关闭时,停止服务端,需要用户重新发送广播后再建立连接
            //if(m_AsyncSocketUserTokenList.Count==0)
            //{
            //    Exit();
            //}
        }
예제 #10
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);
     }
 }
예제 #11
0
        /// <summary>
        /// 处理新连接事件
        /// </summary>
        /// <param name="acceptEventArgs"></param>
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            Logger.Instance().InfoFormat("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;
            userToken.ActiveDateTime  = DateTime.Now;
            if (userToken == null || userToken.ConnectSocket == null)
            {
                return;
            }
            //第一次连接要请求序列号
            if (MappingIP != null)
            {
                MappingIP(this, new DataTransmissionEventArgs(userToken));
            }
            if (CreateCommandQueue != null)
            {
                CreateCommandQueue(this, new DataTransmissionEventArgs(userToken));
            }
            try
            {
                //如果 I/O 操作挂起,将返回 true。 操作完成时,将引发 e 参数的 SocketAsyncEventArgs.Completed 事件。
                //如果 I/O 操作同步完成,将返回 false。 在这种情况下,将不会引发 e 参数的 SocketAsyncEventArgs.Completed 事件,
                //并且可能在方法调用返回后立即检查作为参数传递的 e 对象以检索操作的结果。
                bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                if (!willRaiseEvent)
                {
                    lock (userToken)
                    {
                        ProcessReceive(userToken.ReceiveEventArgs);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Instance().ErrorFormat("Accept client {0} error, message: {1}", userToken.ConnectSocket, e.Message);
                Logger.Instance().Error(e.StackTrace);
            }
            if (m_bStartAccept)
            {
                StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
            }
            else
            {
                Logger.Instance().Info("ProcessAccept()->StartAccept Stopped");
            }
        }
예제 #12
0
        /// <summary>
        /// 初始化连接池,及连接个数
        /// </summary>
        private void Init()
        {
            m_AsyncSocketUserTokenPool.Clear();
            AsyncSocketUserToken userToken;

            for (int i = 0; i < m_NumConnections; i++) //按照连接数建立读写对象
            {
                userToken = new AsyncSocketUserToken(m_ReceiveBufferSize);
                userToken.ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted);
                userToken.SendEventArgs.Completed    += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted);
                m_AsyncSocketUserTokenPool.Push(userToken);
            }
        }
예제 #13
0
        /// <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.SocketError == SocketError.Success)
            {
                if (userToken.ReceiveEventArgs.BytesTransferred > 0)
                {
                    int offset = userToken.ReceiveEventArgs.Offset;
                    int count  = userToken.ReceiveEventArgs.BytesTransferred;
                    if (count <= 0)
                    {
                        bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                        if (!willRaiseEvent)
                        {
                            ProcessReceive(userToken.ReceiveEventArgs);
                        }
                    }
                    else
                    {
                        if (DataReceived != null)
                        {
                            DataReceived(this, new DataTransmissionEventArgs(userToken.ReceiveEventArgs.Buffer, offset, count, userToken));
                        }
                        bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                        if (!willRaiseEvent)
                        {
                            ProcessReceive(userToken.ReceiveEventArgs);
                        }
                    }
                }
                else
                {
                    Logger.Instance().ErrorFormat("ProcessReceive()->BytesTransferred = {0}", userToken.ReceiveEventArgs.BytesTransferred);
                }
            }
            else if (userToken.ReceiveEventArgs.SocketError == SocketError.ConnectionReset)
            {
                Logger.Instance().ErrorFormat("ProcessReceive()->userToken.ReceiveEventArgs.SocketError={0}", userToken.ReceiveEventArgs.SocketError);
                CloseClientSocket(userToken);
            }
            else
            {
                Logger.Instance().ErrorFormat("ProcessReceive()->userToken.ReceiveEventArgs.SocketError={0}", userToken.ReceiveEventArgs.SocketError);
            }
        }
예제 #14
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);
            }
        }
        public AsyncSocketInvokeElement(AsyncServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
        {
            m_asyncSocketServer    = asyncSocketServer;
            m_asyncSocketUserToken = asyncSocketUserToken;

            m_netByteOrder = false;

            m_incomingDataParser    = new IncomingDataParser();
            m_outgoingDataAssembler = new OutgoingDataAssembler();

            m_sendAsync = false;

            m_connectDT = DateTime.UtcNow;
            m_activeDT  = DateTime.UtcNow;
        }
예제 #16
0
        /// <summary>
        /// 针对单一SOCKET进行数据发送
        /// </summary>
        /// <param name="connectSocket">需要发送的Socket对象</param>
        /// <param name="sendEventArgs">Socket事件</param>
        /// <param name="buffer">数据区</param>
        /// <param name="offset">数据起始下标</param>
        /// <param name="count">数据字节长度</param>
        /// <returns></returns>
        public bool SendAsyncEvent(AsyncSocketUserToken connectSocket, SocketAsyncEventArgs sendEventArgs, byte[] buffer, int offset, int count)
        {
            if (connectSocket == null)
            {
                return(false);
            }
            sendEventArgs.SetBuffer(buffer, offset, count);
            bool willRaiseEvent = connectSocket.ConnectSocket.SendAsync(sendEventArgs);

            if (!willRaiseEvent)
            {
                return(ProcessSend(sendEventArgs));
            }
            else
            {
                return(true);
            }
        }
예제 #17
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);
            }
        }
예제 #18
0
        /// <summary>
        /// 初始化服务器
        /// </summary>
        /// <param name="_port">端口</param>
        /// <param name="_parallelNum">最大连接数</param>
        /// <param name="_socketTimeOutMS">超时,单位毫秒</param>
        public SocketServer(int _port, int _parallelNum, int _socketTimeOutMS)
        {
            port            = _port;
            parallelNum     = _parallelNum;
            socketTimeOutMS = _socketTimeOutMS;

            receiveBufferSize        = ProtocolConst.ReceiveBufferSize;
            maxNumberAcceptedClients = new Semaphore(parallelNum, parallelNum);
            asyncSocketUserTokenList = new AsyncSocketUserTokenList();
            asyncSocketUserTokenPool = new AsyncSocketUserTokenPool(parallelNum);

            AsyncSocketUserToken userToken;

            for (int i = 0; i < parallelNum; i++) //按照连接数建立读写对象
            {
                userToken = new AsyncSocketUserToken();
                userToken.ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                userToken.SendEventArgs.Completed    += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                asyncSocketUserTokenPool.Push(userToken);
            }
        }
 public ControlSocketProtocol(AsyncServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "Control";
 }
 public RemoteStreamSocketProtocol(AsyncServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "RemoteStream";
     m_fileStream = null;
 }
 public ThroughputSocketProtocol(AsyncServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "Throughput";
 }