예제 #1
0
        /// <summary>
        /// Run the server. The method will not return until Stop() is called.
        /// </summary>
        public void Run()
        {
            if (authHandler == null)
            {
                authHandler = new DefaultAuthHandler();
            }

            if (fsHandler == null)
            {
                fsHandler = new DefaultFileSystemHandler();
            }

            if (socket == null)
            {
                socket = new TcpListener(endpoint);
            }

            socket.Start();

            // listen for new connections
            try
            {
                while (true)
                {
                    Socket peer = socket.AcceptSocket();

                    IPEndPoint peerPort = (IPEndPoint)peer.RemoteEndPoint;
                    Session    session  = new Session(peer, bufferSize,
                                                      authHandler.Clone(peerPort),
                                                      fsHandler.Clone(peerPort),
                                                      logHandler.Clone(peerPort));

                    session.Start();
                    sessions.Add(session);

                    // purge old sessions
                    for (int i = sessions.Count - 1; i >= 0; --i)
                    {
                        if (!sessions[i].IsOpen)
                        {
                            sessions.RemoveAt(i);
                            --i;
                        }
                    }
                }
            }
            catch (SocketException)
            {
                // ignore, Stop() will probably cause this exception
            }
            finally
            {
                // close all running connections
                foreach (Session s in sessions)
                {
                    s.Stop();
                }
            }
        }