Beispiel #1
0
        /// <summary>
        ///	Server's main loop implementation.
        /// </summary>
        /// <param name="log"> The Logger instance to be used.</param>
        public void Run(Logger log)
        {
            TcpListener srv = null;

            try
            {
                srv = new TcpListener(IPAddress.Loopback, portNumber);
                srv.Start();
                while (true)
                {
                    log.LogMessage("Listener - Waiting for connection requests.");
                    using (TcpClient socket = srv.AcceptTcpClient())
                    {
                        socket.LingerState = new LingerOption(true, 10);
                        log.LogMessage(String.Format("Listener - Connection established with {0}.",
                                                     socket.Client.RemoteEndPoint));
                        // Instantiating protocol handler and associate it to the current TCP connection
                        Handler protocolHandler = new Handler(socket.GetStream(), log);
                        // Synchronously process requests made through de current TCP connection
                        protocolHandler.Run();
                    }

                    Program.ShowInfo(Store.Instance);
                }
            }
            finally
            {
                log.LogMessage("Listener - Ending.");
                srv.Stop();
            }
        }
        /**
         * Processes an accept
         */
        private void AcceptProcessing(IAsyncResult ar)
        {
            TcpClient connection = null;

            try
            {
                connection = srv.EndAcceptTcpClient(ar);

                /**
                 * Increment the number of active connections and, if the we are below of
                 * maximum allowed, start accepting a new connection.
                 */

                int c = Interlocked.Increment(ref activeConnections);
                if (!shutdownInProgress && c < MAX_ACTIVE_CONNECTIONS)
                {
                    srv.BeginAcceptTcpClient(OnAccept, null);
                }

                /**
                 * Start the processing the previously accepted connection.
                 */

                connection.LingerState = new LingerOption(true, 10);
                log.LogMessage(String.Format("Listener - Connection established with {0}.",
                                             connection.Client.RemoteEndPoint));
                // Instantiating protocol handler and associate it to the current TCP connection
                Handler protocolHandler = new Handler(connection.GetStream(), log);
                // Synchronously process requests made through de current TCP connection
                protocolHandler.Run();

                int c2 = Interlocked.Decrement(ref activeConnections);
                if (!shutdownInProgress && c2 == MAX_ACTIVE_CONNECTIONS - 1)
                {
                    srv.BeginAcceptTcpClient(OnAccept, null);
                }
                else if (shutdownInProgress && c2 == 1)
                {
                    //sinalize the blocked thread on shutdown
                    shutdownEvent.Set();
                }
                else if (shutdownInProgress && c2 == 0)
                {
                    //if shutdownInProgress and are not connections pending, i was the command with shutdown and i sinalize the main thread
                    serverIdle.Set();
                    srv.Stop();
                }
            }
            catch (SocketException sockex)
            {
                Console.WriteLine("***socket exception: {0}", sockex.Message);
            }
            catch (ObjectDisposedException)
            {
                /**
                 * benign exceptions that occurs when the server shuts down
                 * and stops listening to the server socket.
                 */
            }
        }
Beispiel #3
0
        private async Task ProcessConnectionAsync(TcpClient connection)
        {
            NetworkStream stream = null;

            try
            {
                // Get a stream for reading and writing through the socket.

                stream = connection.GetStream();


                connection.LingerState = new LingerOption(true, 10);

                log.LogMessage($"Listener - Connection established with {connection.Client.RemoteEndPoint}.");
                // Instantiating protocol handler and associate it to the current TCP connection
                Handler protocolHandler = new Handler(connection.GetStream(), log);
                // Synchronously process requests made through de current TCP connection
                await protocolHandler.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine("***error:: {0}", ex.Message);
            }
            finally
            {
                // close everything
                if (stream != null)
                {
                    stream.Close();
                }
                connection.Close();
            }
        }
Beispiel #4
0
        /// <summary>
        ///	Server's main loop implementation.
        /// </summary>
        /// <param name="log"> The Logger instance to be used.</param>
        public void Run(Logger log)
        {
            TcpListener srv = null;
            try
            {
                srv = new TcpListener(IPAddress.Loopback, portNumber);
                srv.Start();
                while (true)
                {
                    log.LogMessage("Listener - Waiting for connection requests.");
                    using (TcpClient socket = srv.AcceptTcpClient())
                    {
                        socket.LingerState = new LingerOption(true, 10);
                        log.LogMessage(String.Format("Listener - Connection established with {0}.",
                            socket.Client.RemoteEndPoint));
                        // Instantiating protocol handler and associate it to the current TCP connection
                        Handler protocolHandler = new Handler(socket.GetStream(), log);
                        // Synchronously process requests made through de current TCP connection
                        protocolHandler.Run();
                    }

                    Program.ShowInfo(Store.Instance);
                }
            }
            finally
            {
                log.LogMessage("Listener - Ending.");
                srv.Stop();
            }
        }
Beispiel #5
0
        /**
         * Processes an accept
         */
        private void AcceptProcessing(IAsyncResult ar)
        {
            TcpClient     connection = null;
            NetworkStream stream     = null;

            try
            {
                connection = server.EndAcceptTcpClient(ar);

                /**
                 * Increment the number of active connections and, if the we are below of
                 * maximum allowed, start accepting a new connection.
                 */

                int c = Interlocked.Increment(ref activeConnections);
                if (c < MAX_ACTIVE_CONNECTIONS)
                {
                    server.BeginAcceptTcpClient(OnAccept, null);
                }



                stream = connection.GetStream();


                connection.LingerState = new LingerOption(true, 10);

                log.LogMessage($"Listener - Connection established with {connection.Client.RemoteEndPoint}.");
                // Instantiating protocol handler and associate it to the current TCP connection
                Handler protocolHandler = new Handler(connection.GetStream(), log);
                // Synchronously process requests made through de current TCP connection
                protocolHandler.Run();

                /**
                 * When the processing of the connection is completed, decrement the number of active
                 * connections. If the number of active connections
                 * was equal to the maximum allowed, we must accept a new connection.
                 * Otherwise, if the number of active connections drops to zero and the shut down
                 * was initiated, set the server idle event.
                 */

                int c2 = Interlocked.Decrement(ref activeConnections);
                if (c2 == MAX_ACTIVE_CONNECTIONS - 1)
                {
                    server.BeginAcceptTcpClient(OnAccept, null);
                }
                else if (c2 == 0)
                {
                    Console.WriteLine("\n--Finishing on Callback--\n");
                }
            }
            catch (SocketException sockex)
            {
                Console.WriteLine("***socket exception: {0}", sockex.Message);
            }
            catch (ObjectDisposedException)
            {
                /**
                 * benign exceptions that occurs when the server shuts down
                 * and stops listening to the server socket.
                 */
            }
            finally
            {
                // anyway, close stream and close client socket
                stream?.Close();
                connection?.Close();
            }
        }
Beispiel #6
0
        /// <summary>
        ///	Server's main loop implementation.
        /// </summary>
        /// <param name="log"> The Logger instance to be used.</param>
        public Task<Boolean> Run(Logger log)
        {
            TcpListener srv = null;
            
            try
            {

                srv = new TcpListener(IPAddress.Loopback, portNumber);
                srv.Start();
                /////////////////////////////////////////////////////////////////
                /////////////////////////////APM/////////////////////////////////
                /////////////////////////////////////////////////////////////////
                AsyncCallback onAccepted = null;
                onAccepted = delegate(IAsyncResult ar)
                    {
                        TcpClient socket = null;

                        try
                        {
                            int timeout = (int)ar.AsyncState;
                            if (timeout == 0)
                                return;

                            int time = Environment.TickCount;

                            using (socket = srv.EndAcceptTcpClient(ar))
                            {
                                if(Environment.TickCount - time > timeout)
                                    return;
                                socket.LingerState = new LingerOption(true, 10);
                                log.LogMessage(String.Format("Listener - Connection established with {0}.",
                                                             socket.Client.RemoteEndPoint));
                                log.IncrementRequests();
                                // Instantiating protocol handler and associate it to the current TCP connection
                                Handler protocolHandler = new Handler(socket.GetStream(), log);
                                // Synchronously process requests made through de current TCP connection
                                protocolHandler.Run();

                                srv.BeginAcceptTcpClient(onAccepted, null);
                            }
                            Program.ShowInfo(Store.Instance);
                        }
                        catch (SocketException) { Console.WriteLine("Socket error"); }
                        catch (ObjectDisposedException) { }
                    };
                srv.BeginAcceptTcpClient(onAccepted, 20);
                Console.ReadLine();
                return null;
                //////////////////////////////////////////////////////
                //////////////////////////////////////////////////////
                //while (true)
                //{
                //    log.LogMessage("Listener - Waiting for connection requests.");
                //    using (TcpClient socket = srv.AcceptTcpClient())
                //    {
                //        socket.LingerState = new LingerOption(true, 10);
                //        log.LogMessage(String.Format("Listener - Connection established with {0}.",
                //            socket.Client.RemoteEndPoint));
                //        // Instantiating protocol handler and associate it to the current TCP connection
                //        Handler protocolHandler = new Handler(socket.GetStream(), log);
                //        // Synchronously process requests made through de current TCP connection
                //        protocolHandler.Run();
                //    }

                //    Program.ShowInfo(Store.Instance);
                //}

            }
            finally
            {
                log.LogMessage("Listener - Ending.");
                srv.Stop();
            }
        }
Beispiel #7
0
        /// <summary>
        ///	Server's main loop implementation.
        /// </summary>
        /// <param name="log"> The Logger instance to be used.</param>
        public async Task Run(Logger log, CancellationToken ctk)
        {
            // Create a listen socket bind to the server port.
            server = new TcpListener(IPAddress.Loopback, portNumber);

            // Start listen from server socket
            server.Start();

            try
            {
                var startedTasks = new HashSet <Task>();
                do
                {
                    try
                    {
                        var connection = await server.AcceptTcpClientAsync();

                        /**
                         * Start the processing the previously accepted connection.
                         */

                        connection.LingerState = new LingerOption(true, 10);
                        log.LogMessage(String.Format("Listener - Connection established with {0}.",
                                                     connection.Client.RemoteEndPoint));

                        Handler protocolHandler = new Handler(connection.GetStream(), log);
                        // Synchronously process requests made through de current TCP connection


                        Interlocked.Increment(ref activeConnections);

                        //
                        // Add the listen thread returned by the protocolHandler.Run method
                        // to the thread hast set.
                        //

                        startedTasks.Add(protocolHandler.Run().ContinueWith(_ =>
                        {
                            int c2 = Interlocked.Decrement(ref activeConnections);
                            if (c2 == 1 && ctk.IsCancellationRequested)
                            {
                                shutdownEvent.Set();
                            }
                            if (c2 == 0 && ctk.IsCancellationRequested)
                            {
                                server.Stop();
                            }
                        }));

                        //
                        // If the threshold was reached, wait until one of the active
                        // worker threads complete its processing.
                        //

                        if (startedTasks.Count >= MAX_SIMULTANEOUS_CONNECTIONS)
                        {
                            startedTasks.Remove(await Task.WhenAny(startedTasks));
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        // benign exception
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("***error: {0}", ex.Message);
                    }
                } while (!ctk.IsCancellationRequested);


                /**
                 * before return, wait for completion of processing of all the accepted requests.
                 */
                server.Stop();
                await Task.WhenAll(startedTasks);
            }
            finally
            {
                log.LogMessage("Listener - Ending.");
                //onde faço stop?
            }
        }