TrotiNet.TcpServer.Stop C# (CSharp) Method

Stop() public method

Stop the listening threads and close the client sockets
public Stop ( ) : void
return void
        public void Stop()
        {
            if (ListeningThread == null)
                return;

            log.Debug("Shutting down server");
            IsShuttingDown = true;

            ListenThreadSwitch.Set();

            CleanTimer.Dispose();
            CleanTimer = null;

            if (ListeningThread.IsAlive)
            {
                // Create a connection to the port to unblock the
                // listener thread
                using (var sock = new Socket(AddressFamily.Unspecified,
                    SocketType.Stream, ProtocolType.Tcp))
                {
                    try
                    {
                        sock.Connect(new IPEndPoint(IPAddress.Loopback,
                            this.LocalPort));
                        sock.Close();
                    } catch { /* ignore */ }
                }

                if (ListeningThread.ThreadState == ThreadState.WaitSleepJoin)
                    ListeningThread.Interrupt();
                Thread.Sleep(1000);
                ListeningThread.Abort();
            }

            ListeningThread = null;
            IsListening = false;

            log.Info("Server stopped");
        }