Beispiel #1
0
        private void OperationCompleted(object sender, SocketAsyncEventArgs e)
        {
            e.Completed -= OperationCompleted;

            switch (e.LastOperation)
            {
            case SocketAsyncOperation.Receive:
                ProcessNetwork(e);

                SocketPool.Add(e);
                break;

            case SocketAsyncOperation.Send:
                IPacket packet = e.UserToken as IPacket;

                if (packet is DisconnectPacket)
                {
                    Client.Client.Shutdown(SocketShutdown.Send);
                    Client.Close();

                    cancel.Cancel();
                }

                e.SetBuffer(null, 0, 0);
                break;
            }
        }
Beispiel #2
0
    /// <summary>
    /// 异步Socket TCP服务器
    /// </summary>
    /// <param name="localIPAddress">监听的IP地址</param>
    /// <param name="portNo">监听的端口</param>
    /// <param name="maxClient">最大客户端数量</param>
    public IOCPServer(string IP, int portNo, int maxClient)
    {
        //this.Address = localIPAddress;
        //this.Port = listenPort;
        //this.Encoding = Encoding.Default;

        //_serverSock = new Socket(localIPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        //_bufferManager = new BufferManager(_bufferSize * maxClient * opsToPreAlloc, _bufferSize);

        //_objectPool = new SocketAsyncEventArgsPool(maxClient);

        //_maxAcceptedClients = new Semaphore(maxClient, maxClient);


        Console.WriteLine("初始化服务器。");


        try
        {
            IPAddress ipAddress = IPAddress.Parse(IP);
            _serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _serverSock.Bind(new IPEndPoint(ipAddress, portNo));
            _serverSock.Listen(maxClient);

            _objectPool = new SocketAsyncEventArgsPool(maxClient);
            for (int i = 0; i < maxClient; i++) //填充SocketAsyncEventArgs池
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += new EventHandler <SocketAsyncEventArgs>(OnIOCompleted);
                _objectPool.Add(args);
            }

            Thread tCheckClientHeartbeat = new Thread(CheckClientHeartbeat);
            tCheckClientHeartbeat.IsBackground = true;
            tCheckClientHeartbeat.Start();

            StartAccept(null);
        }
        catch (Exception error)
        {
            Console.WriteLine(error.Message);
        }
    }