Ejemplo n.º 1
0
        /// <summary>
        /// 循环接受连接
        /// </summary>
        /// <param name="acceptEventArgs"></param>
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            //Program.Logger.InfoFormat("Client connection accepted. Local Address: {0}, Remote Address: {1}", acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);

            //从连接池中分配一个连接赋给当前连接
            AsyncSocketUserToken userToken = m_asyncSocketUserTokenPool.Pop();

            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)
            {
                Program.Logger.ErrorFormat("Accept client {0} error, message: {1}, trace:{2}", userToken.ConnectSocket, E.Message, E.StackTrace);
                //Program.Logger.Error(E.StackTrace);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 接收链接后的处理过程
        /// </summary>
        /// <param name="e"></param>
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            //Program.Logger.InfoFormat("Client connection accepted. Local Address: {0}, Remote Address: {1}", acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);

            //从连接池中分配一个连接赋给当前连接
            AsyncSocketUserToken userToken = m_asyncSocketUserTokenPool.Pop();

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

            try
            {
                // As soon as the client is connected, post a receive to the connection
                bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs);
                if (!willRaiseEvent)
                {
                    lock (userToken)
                    {
                        ProcessReceive(userToken.ReceiveEventArgs);
                    }
                }
            }
            catch (Exception E)
            {
                Program.Logger.ErrorFormat("Accept client {0} error, message: {1}, trace:{2}", userToken.ConnectSocket, E.Message, E.StackTrace);
                //Program.Logger.Error(E.StackTrace);
            }

            // Accept the next connection request
            StartAccept(e);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="numConnections"></param>
        public AsyncSocketServer(int numConnections)
        {
            m_numConnections    = numConnections;
            m_receiveBufferSize = ProtocolConst.ReceiveBufferSize;

            m_asyncSocketUserTokenPool = new AsyncSocketUserTokenPool(numConnections);
            AsyncSocketUserTokenList   = new AsyncSocketUserTokenList();
            m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);
        }
Ejemplo n.º 4
0
        public AsyncSocketServer(int numConnections)
        {
            m_numConnections    = numConnections;
            m_receiveBufferSize = ProtocolConst.ReceiveBufferSize;

            m_asyncSocketUserTokenPool = new AsyncSocketUserTokenPool(numConnections);
            m_asyncSocketUserTokenList = new AsyncSocketUserTokenList();
            m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);

            m_logOutputSocketProtocolMgr = new LogOutputSocketProtocolMgr();
            m_uploadSocketProtocolMgr    = new UploadSocketProtocolMgr();
            m_downloadSocketProtocolMgr  = new DownloadSocketProtocolMgr();
        }
Ejemplo n.º 5
0
        public AsyncSocketServer(int numConnections)
        {
            m_numConnections = numConnections;//设置服务器最大并发访问数
            m_receiveBufferSize = ProtocolConst.ReceiveBufferSize;//设置接收缓存区大小

            m_asyncSocketUserTokenPool = new AsyncSocketUserTokenPool(numConnections);//设置AsyncSocketUserTokenPool缓冲池的大小(栈实现)
            m_asyncSocketUserTokenList = new AsyncSocketUserTokenList();//初始化AsyncSocketUserToken列表
            m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);//初始化信号量(有点不太懂)

            //-----------------------未看------------------------------//
            m_logOutputSocketProtocolMgr = new LogOutputSocketProtocolMgr();//日志输出对象
            m_uploadSocketProtocolMgr = new UploadSocketProtocolMgr();//上传
            //-----------------------未看------------------------------//
        }
        /// <summary>
        /// 初始化函数
        /// </summary>
        public void Init()
        {
            _totalBytesRead = 0;

            _clientCount = 0;

            _bufferManager = new BufferManager(_bufferSize * _maxClient * (opsToPreAlloc), _bufferSize);

            _userTokenPool = new AsyncSocketUserTokenPool(_maxClient);

            _clientList = new AsyncSocketUserTokenList();

            _maxAcceptClientSem = new Semaphore(_maxClient, _maxClient);

            _stopWaitSem = new Semaphore(1, 1);

            _logOutEvtArgsPool = new Stack <LogOutEventArgs>(_maxClient);

            // preallocate pool of AsyncSocketUserToken and LogOutEventArgs
            AsyncSocketUserToken userToken;
            LogOutEventArgs      logArgs;

            for (int i = 0; i < _maxClient; i++)
            {
                //Pre-allocate a set of reusable AsyncSocketUserToken
                userToken = new AsyncSocketUserToken();
                userToken.SendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted);
                userToken.RecvEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted);

                // assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
                _bufferManager.SetBuffer(userToken.RecvEventArgs);
                _bufferManager.SetBuffer(userToken.SendEventArgs);

                _userTokenPool.Push(userToken);

                // Pre-allocate a set of reusable LogOutEventArgs
                logArgs = new LogOutEventArgs("", 0, 0);
                _logOutEvtArgsPool.Push(logArgs);
            }
        }
        /// <summary>
        /// 停止服务
        /// </summary>
        public void Stop()
        {
            if (IsRunning)
            {
                IsRunning = false;

                _stopWaitSem.WaitOne();

                _daemonThread.Close();
                //_serverSock.Close();

                //TODO 关闭对所有客户端的连接
                AsyncSocketUserToken[] users = null;
                _clientList.CopyList(ref users);
                foreach (AsyncSocketUserToken u in users)
                {
                    CloseClientSocket(u.RecvEventArgs);
                }
                users = null;

                _stopWaitSem.Release();

                _serverSock.Close();
                _clientList.Clear();
                _userTokenPool.Clear();

                _serverSock         = null;
                _clientList         = null;
                _userTokenPool      = null;
                _bufferManager      = null;
                _maxAcceptClientSem = null;

                Log4Debug("服务器已关闭....");
            }

            GC.Collect();
        }
Ejemplo n.º 8
0
        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);

            Program.Logger.InfoFormat("Client connection disconnected. {0}", socketInfo);
            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                Program.Logger.ErrorFormat("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message);
            }
            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源

            m_maxNumberAcceptedClients.Release();
            m_asyncSocketUserTokenPool.Push(userToken);
            AsyncSocketUserTokenList.Remove(userToken);
        }