Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.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/3/sockets/2.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# 试图从NetworkStream读取数据会使程序崩溃,没有异常或错误_C#_Sockets_Stream - Fatal编程技术网

C# 试图从NetworkStream读取数据会使程序崩溃,没有异常或错误

C# 试图从NetworkStream读取数据会使程序崩溃,没有异常或错误,c#,sockets,stream,C#,Sockets,Stream,我试图从套接字读取数据,但是每当我试图读取整个流时,我的程序就会挂起。没有错误或例外 我可以手动读取,比如说4个字节,它会工作,但是我不再知道服务器将发送的数据的确切大小,因此我希望读取整个流。我做错了什么 调用ReadToEnd()时挂起 您的代码不知道流有多长,它可能还没有结束,所以它将继续阻塞,直到结束为止。下面是一个示例服务器和客户端(绝不是一个健壮的实现< /强>),但是如果您考虑下面的代码,您应该看到如何发送请求并接收响应: public class Server {

我试图从套接字读取数据,但是每当我试图读取整个流时,我的程序就会挂起。没有错误或例外

我可以手动读取,比如说4个字节,它会工作,但是我不再知道服务器将发送的数据的确切大小,因此我希望读取整个流。我做错了什么

调用ReadToEnd()时挂起


您的代码不知道流有多长,它可能还没有结束,所以它将继续阻塞,直到结束为止。下面是一个示例服务器和客户端(<强>绝不是一个健壮的实现< /强>),但是如果您考虑下面的代码,您应该看到如何发送请求并接收响应:

    public class Server
    {
        private readonly Thread _listenThread;
        private readonly TcpListener _tcpListener;

        public Server()
        {
            _tcpListener = new TcpListener(IPAddress.Any, 3000);
            _listenThread = new Thread(Listen);
            _listenThread.Start();
        }

        private void Listen()
        {
            var tcpListener = _tcpListener;

            if (tcpListener != null)
            {
                tcpListener.Start();
            }

            while (true)
            {
                TcpClient client = _tcpListener.AcceptTcpClient();
                Console.Out.WriteLine("Connection Accepted");
                Thread clientThread = new Thread(DoWork);
                clientThread.Start(client);
            }
        }

        private void DoWork(object client)
        {
            TcpClient tcpClient = client as TcpClient;

            if (tcpClient == null)
            {
                throw new ArgumentNullException("client", "Must pass client in");
            }

            using (NetworkStream clientStream = tcpClient.GetStream())
            {
                byte[] message = new byte[1024];

                while (true)
                {
                    Console.Out.WriteLine("Waiting for message");
                    int bytesRead = clientStream.Read(message, 0, 1024);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    ASCIIEncoding encoder = new ASCIIEncoding();
                    string received = encoder.GetString(message, 0, bytesRead);

                    Console.Out.WriteLine(String.Format("Read {0}", received));
                    if (received.Equals("Hello Server !"))
                    {
                        byte[] buffer = encoder.GetBytes("Hello Client!");
                        clientStream.Write(buffer, 0, buffer.Length);
                        clientStream.Flush();
                    }
                }
            }
        }
    }
你需要一个这样做的客户

    static void Main(string[] args)
    {
        try
        {

            using (TcpClient clientSock = new TcpClient(IPAddress.Loopback.ToString(), 3000))
            {
                using (Stream clientStream = clientSock.GetStream())
                {
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    byte[] helloMessage = encoder.GetBytes("Hello Server !");

                    clientStream.Write(helloMessage, 0, helloMessage.Length);
                    clientStream.Flush();

                    using (StreamReader streamReader = new StreamReader(clientStream))
                    {
                        while(true)
                        {
                            char[] buffer = new char[1024];
                            streamReader.Read(buffer,0, 1024);

                            Console.Out.WriteLine(new string(buffer));
                        }
                    }
                }
            }

            Console.ReadLine();
        }
        catch (Exception)
        {
            // do something here

            throw;
        }
    }

您的代码不知道流有多长,它可能还没有结束,所以它将继续阻塞,直到结束为止。下面是一个示例服务器和客户端(<强>绝不是一个健壮的实现< /强>),但是如果您考虑下面的代码,您应该看到如何发送请求并接收响应:

    public class Server
    {
        private readonly Thread _listenThread;
        private readonly TcpListener _tcpListener;

        public Server()
        {
            _tcpListener = new TcpListener(IPAddress.Any, 3000);
            _listenThread = new Thread(Listen);
            _listenThread.Start();
        }

        private void Listen()
        {
            var tcpListener = _tcpListener;

            if (tcpListener != null)
            {
                tcpListener.Start();
            }

            while (true)
            {
                TcpClient client = _tcpListener.AcceptTcpClient();
                Console.Out.WriteLine("Connection Accepted");
                Thread clientThread = new Thread(DoWork);
                clientThread.Start(client);
            }
        }

        private void DoWork(object client)
        {
            TcpClient tcpClient = client as TcpClient;

            if (tcpClient == null)
            {
                throw new ArgumentNullException("client", "Must pass client in");
            }

            using (NetworkStream clientStream = tcpClient.GetStream())
            {
                byte[] message = new byte[1024];

                while (true)
                {
                    Console.Out.WriteLine("Waiting for message");
                    int bytesRead = clientStream.Read(message, 0, 1024);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    ASCIIEncoding encoder = new ASCIIEncoding();
                    string received = encoder.GetString(message, 0, bytesRead);

                    Console.Out.WriteLine(String.Format("Read {0}", received));
                    if (received.Equals("Hello Server !"))
                    {
                        byte[] buffer = encoder.GetBytes("Hello Client!");
                        clientStream.Write(buffer, 0, buffer.Length);
                        clientStream.Flush();
                    }
                }
            }
        }
    }
你需要一个这样做的客户

    static void Main(string[] args)
    {
        try
        {

            using (TcpClient clientSock = new TcpClient(IPAddress.Loopback.ToString(), 3000))
            {
                using (Stream clientStream = clientSock.GetStream())
                {
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    byte[] helloMessage = encoder.GetBytes("Hello Server !");

                    clientStream.Write(helloMessage, 0, helloMessage.Length);
                    clientStream.Flush();

                    using (StreamReader streamReader = new StreamReader(clientStream))
                    {
                        while(true)
                        {
                            char[] buffer = new char[1024];
                            streamReader.Read(buffer,0, 1024);

                            Console.Out.WriteLine(new string(buffer));
                        }
                    }
                }
            }

            Console.ReadLine();
        }
        catch (Exception)
        {
            // do something here

            throw;
        }
    }

你说的“撞车”是什么意思?你正在读一条小溪,它可以无限长。如果您的程序是单线程的,那么很有可能您还没有完成ReadToEnd()。我应该说它挂起了,它不会超过这一行。但是,如果我读取的是5字节而不是4字节,它也会以相同的方式挂起。在streamreader帮助页面中:ReadToEnd假设流知道何时结束。对于交互式协议,在这种协议中,服务器仅在您请求数据时才发送数据,并且不关闭连接,ReadToEnd可能会无限期阻塞,因为它没有到达终点,因此应该避免。您如何知道服务器何时完成向您发送数据?您所说的“崩溃”是什么意思?你正在读一条小溪,它可以无限长。如果您的程序是单线程的,那么很有可能您还没有完成ReadToEnd()。我应该说它挂起了,它不会超过这一行。但是,如果我读取的是5字节而不是4字节,它也会以相同的方式挂起。在streamreader帮助页面中:ReadToEnd假设流知道何时结束。对于交互式协议,在这种协议中,服务器仅在您请求数据时才发送数据,并且不关闭连接,ReadToEnd可能会无限期阻塞,因为它没有到达终点,因此应该避免。您如何知道服务器何时完成向您发送数据?