簡體   English   中英

在C#中的單獨線程上停止異步TCP服務器

[英]Stopping an asynchronous TCP server on separate thread in C#

我已經實現了由另一個進程生成的異步TCP服務器。 它開始正常並按預期運行,但是當我結束啟動它的進程時,我無法終止服務器。

以下是我當前的TCP服務器和其他進程的停止功能。

TCP服務器

    public class StateObject
    {
        //Client socket.
        public Socket workSocket = null;
        //Size of receive buffer.
        public const int BufferSize = 1024;
        //Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        //Received data string.
        public StringBuilder sb = new StringBuilder();
    }

    public class AsynchronousSocketListener : Strategy
    {
        //Thread signal.
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        public volatile bool listening = true;

        //User-specified port number.
        private int Port;

        public AsynchronousSocketListener(int port)
        {
            Port = port;
        }

        public void StopListening()
        {
            listening = false;
        }

        public void StartListening()
        {
            //Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            //Establish the local endpoint for the socket.
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port);

            //Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            //Bind the socket to the local endpoint and listen for
            //incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (listening)
                {
                    //Set the event to nonsignaled state.
                    allDone.Reset();    

                    //Start an asychronous socket to listen for connections.
                    Print("Waiting for a connection...");
                    listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                        listener);

                    //Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Print(e.ToString());    
            }
        }

        public void AcceptCallback(IAsyncResult arg)
        {
            //Signal the main thread to continue.
            allDone.Set();

            //Get the socket that handles the client request.
            Socket listener = (Socket) arg.AsyncState;
            Socket handler = listener.EndAccept(arg);

            //Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }

        public void ReadCallback(IAsyncResult arg)
        {
            String content = String.Empty;

            //Retrieve the state object and the handler socket
            //from the asynchronous state object.
            StateObject state = (StateObject) arg.AsyncState;
            Socket handler = state.workSocket;

            //Read data from the client socket.
            int bytesRead = handler.EndReceive(arg);

            if (bytesRead > 0)
            {
                //There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(
                    state.buffer,0,bytesRead));

                //Check for end-of-file tag. If it is not there, read
                //more data.
                content = state.sb.ToString();
                if (content.IndexOf("<EOF>") > -1)
                {
                    //All the data has been read from the
                    //client. Display it on the console.
                    Print("Read " + content.Length + " bytes from socket. \n Data : " + content);
                    //Echo the data back to the client.
                    Send(handler, content);
                }
                else
                {
                    //Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                }
            }
        }

        private void Send(Socket handler, String data)
        {
            //Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            //Begin sending the data to the remote device.
            handler.BeginSend(byteData,0,byteData.Length,0,
                new AsyncCallback(SendCallback),handler);
        }

        private void SendCallback(IAsyncResult arg)
        {
            try
            {
                //Retrieve the socket from the state object.
                Socket handler = (Socket) arg.AsyncState;

                //Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(arg);
                Print("Sent " + bytesSent + " bytes to client.");

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                Print(e.ToString());    
            }
        }
    }

產卵過程

//private NinjaTerminal.Server server;
        private NinjaTerminal.AsynchronousSocketListener    server;
        private Thread                                      listenThread;
        private int                                         _Port = 8080;

    protected override void OnStartUp() 
    {
        server = new NinjaTerminal.AsynchronousSocketListener(Port);
        listenThread = new Thread(new ThreadStart(server.StartListening));
        listenThread.Start();
    }

    protected override void OnTermination() 
    {
        listenThread.stopListening();
        listenThread.Join();
    }

現在我已經驗證了OnTermination()被調用,並且它確實連接到服務器線程,但是服務器線程永遠不會結束。

我會喜歡一些關於為什么的見解,以及對更好的建築或更多歡迎的建議。 在這個階段,除了設置TCP服務器之外,我沒有投入太多資金,所以如果你有不同/更好的想法,我很樂意聽到它。

此外,我已經通過StackOverflow搜索了高低,以獲得答案,並且它們都沒有真正應用於異步TCP服務器。 我正在使用.NET 3.5

代碼添加到里德的答案

public void StopListening(){listening = false; allDone.Set(); }

    public void StartListening()
    {
        //Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        //Establish the local endpoint for the socket.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port);

        //Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        //Bind the socket to the local endpoint and listen for
        //incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (listening)
            {
                //Set the event to nonsignaled state.
                allDone.Reset();    

                //Start an asychronous socket to listen for connections.
                Print("Waiting for a connection...");
                listener.BeginAccept(
                new AsyncCallback(AcceptCallback),
                    listener);

                //Wait until a connection is made before continuing.
                allDone.WaitOne();
            }
            listener.Close();
        }
        catch (Exception e)
        {
            Print(e.ToString());    
        }
    }

您需要更改StopListening以包含一個調用WaitHandle的信號:

public void StopListening()
{
    this.listening = false;
    this.allDone.Set();
}

如果沒有這個,您的StartListening例程將永遠掛起:

//Wait until a connection is made before continuing.
allDone.WaitOne();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM