Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中停止单独线程上的异步TCP服务器#_C#_Asynchronous_Tcp_Blocking - Fatal编程技术网

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

C# 在C中停止单独线程上的异步TCP服务器#,c#,asynchronous,tcp,blocking,C#,Asynchronous,Tcp,Blocking,我已经实现了一个由另一个进程派生的异步TCP服务器。它启动正常并按预期运行,但是在结束启动服务器的进程时,我在终止服务器时遇到问题 以下是我当前的TCP服务器和另一进程的停止功能 TCP服务器 public class StateObject { //Client socket. public Socket workSocket = null; //Size of receive buffer. public con

我已经实现了一个由另一个进程派生的异步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());    
            }
        }
    }
现在我已经验证了OnTermination()被调用,并且它确实加入到服务器线程,但是服务器线程永远不会结束

我想了解一下原因,并对更好的体系结构提出一些建议。在这个阶段,除了设置TCP服务器,我没有在任何方面投入太多,所以如果您有不同/更好的想法,我很乐意听到

此外,我已经在StackOverflow上下搜索了答案,但没有一个真正应用于异步TCP服务器。我使用的是.NET3.5

为里德的答案添加代码

    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());    
            }
        }
    }
公营部门 { 倾听=错误; 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();

啊,现在我尝试了你刚才建议的一种变体,但我使用了allDone.WaitOne();在我的StopListening()方法中,而不是在allDone.Set()中;为了补充这个答案,因为它还没有完全完成,在我设置Listing To false并且StartListening例程可以重新开始并退出while循环之后,我仍然需要关闭侦听器。我已经用相关的代码编辑了这个问题,因为注释不是这种事情的合适位置。@Zach:我只是想告诉你为什么“服务器线程永远不会结束”;)啊,你肯定做到了,这就是我的问题。谢谢你的洞察力,我真的被困在那里了。