コード例 #1
0
ファイル: NettyServer.cs プロジェクト: haoljp/SharpNetty
        /// <summary>
        /// Begins listening for and accepting socket connections.
        /// </summary>
        /// <param name="backLog">Maximum amount of pending connections</param>
        public void Listen(int backLog = 25, int maximumConnections = 60)
        {
            _connections = new Connection[maximumConnections];

            var listenerThread = new Thread(() =>
            {
                int index = -1;

                if (_socketAddress == null)
                {
                    throw new Exception("You must specifiy the socket address before calling the listen method!");
                }
                if (!MainSocket.IsBound)
                {
                    throw new Exception("You must bind the socket before calling the listen method!");
                }

                MainSocket.Listen(backLog);

                Console.WriteLine("[NettyServer] Server listening on address: " + MainSocket.LocalEndPoint);

                while (true)
                {
                    var incomingSocket = MainSocket.Accept();

                    for (int i = 0; i < maximumConnections; i++)
                    {
                        if (_connections[i] == null)
                        {
                            _connections[i] = new Connection(incomingSocket, this)
                            {
                                Socket = { NoDelay = MainSocket.NoDelay }
                            };

                            index = i;
                            break;
                        }
                    }

                    Console.WriteLine("[NettyServer] Received a connection from: " + incomingSocket.RemoteEndPoint);

                    if (Handle_NewConnection != null)
                    {
                        Handle_NewConnection.Invoke(index);
                    }

                    try
                    {
                        Thread recThread = new Thread(x => BeginReceiving(incomingSocket, index));
                        recThread.Name   = incomingSocket.RemoteEndPoint + ": incoming data thread.";
                        recThread.Start();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }
            })
            {
                Name = "NettyServer Incoming Connection Thread"
            };

            listenerThread.Start();
        }