【问题标题】:Trying to read from NetworkStream crashes program, no exception or error尝试从 NetworkStream 读取崩溃程序,没有异常或错误
【发布时间】:2012-03-19 03:26:08
【问题描述】:

我正在尝试从套接字读取数据,但是每当我尝试读取整个流时,我的程序都会挂起。没有错误或异常。

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

调用 ReadToEnd() 时挂起。

Stream input = socket.GetStream();

byte[] request = new byte[5];

input.Write(request, 0, 5); //send request

StreamReader reader = new StreamReader(input);

if (input.CanRead == true)
{
    string test = reader.ReadToEnd();
}

【问题讨论】:

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

标签: c# sockets stream


【解决方案1】:

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

    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;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2012-02-15
    • 1970-01-01
    • 2014-06-24
    • 2017-10-23
    • 2011-12-29
    • 1970-01-01
    相关资源
    最近更新 更多