在C#中使用单独的线程停止异步TCP服务器

3
我已经实现了一个由另一个进程生成的异步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。 Reed的答案代码添加 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());    
        }
    }
1个回答

5
你需要修改 StopListening 方法,加入一个通知 WaitHandle 的调用:
public void StopListening()
{
    this.listening = false;
    this.allDone.Set();
}

没有这个,你的StartListening例程将永远停留在这里:
//Wait until a connection is made before continuing.
allDone.WaitOne();

啊,现在我已经尝试了你刚才建议的一个变体,但是我在我的StopListening()方法中使用了allDone.WaitOne();而不是allDone.Set(); - zkwentz
为了补充这个答案,因为它还不完整,在我将listening设置为false并且StartListening例程可以重新开始并退出while循环之后,我仍然需要关闭监听器。我已经编辑了相关代码的问题,因为注释不是那种东西的适当位置。 - zkwentz
1
@Zach:我只是想向你展示一下为什么“服务器线程永远不会结束” ;) - Reed Copsey
啊,你肯定做到了,这正是我的问题。感谢你的见解,我真的卡在那里了。 - zkwentz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接