Exemple #1
0
 public TCPSocketClient()
 {
     BufferSize            = 1024 * 1024 * 10;
     PacketMgr             = new PacketMgr();
     SocketToken           = new AsyncUserToken(this, BufferSize);
     SocketToken.IsClient  = true;
     SocketToken.PacketMgr = PacketMgr;
     SocketToken.RecvEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
     SocketToken.SendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
 }
Exemple #2
0
        public TCPSocketServer(int numConnections)
        {
            int max = ushort.MaxValue;

            if (numConnections < max)
            {
                NumConnections = numConnections;
                BufferSize     = 1024 * 10; // IOCP接收数据缓存大小,设置过小会造成事件响应增多,设置过大会造成内存占用偏多

                PacketMgr                = new PacketMgr();
                MaxNumberAccepted        = new Semaphore(NumConnections, NumConnections);
                AsyncSocketUserTokenUsed = new List <AsyncUserToken>();
                AsyncSocketUserTokenPool = new ObjectPool <AsyncUserToken>(numConnections);

                AsyncUserToken socketToken;

                for (int i = 0; i < NumConnections; i++) //按照连接数建立读写对象
                {
                    socketToken           = new AsyncUserToken(this, BufferSize);
                    socketToken.TokenID   = i + 1;
                    socketToken.IsClient  = false;
                    socketToken.PacketMgr = PacketMgr;
                    socketToken.RecvEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                    socketToken.SendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                    AsyncSocketUserTokenPool.Push(socketToken);
                }

                SocketTimeOutMS         = 30 * 1000;                         // 30秒
                DaemonThread            = new TCPSocketServerDaemonThread(); // 线程守护
                DaemonThread.TCPServer  = this;
                DaemonThread.UserTokens = AsyncSocketUserTokenUsed;
                DaemonThread.Start();
            }
            else
            {
                throw new Exception(string.Format("链接数{0}超出最大连接数{1}", numConnections, max));
            }
        }