【问题标题】:Unable to Read byte Stream in C#无法在 C# 中读取字节流
【发布时间】:2012-04-15 18:39:01
【问题描述】:

我正在构建一个客户端服务器应用程序,其中客户端必须发送一些字节流,并且服务器根据从客户端接收到的字节来响应它。我正在使用NetworkStream.WriteNetworkStream.Read 方法来发送和接收数据。客户端能够创建到服务器的 TCP 连接。接受连接后,服务器执行NetworkStream.Read 并等待来自客户端的一些输入。客户端使用NetworkStream.Write 发送数据,也使用NetworkStream.Flush。但是服务器永远不会从读取中唤醒。

你们能否建议我这里可能存在什么问题,或者如果您知道在 C# 中通过 TCP 连接发送字节流的任何其他方法,请告诉我。

谢谢!

【问题讨论】:

  • 第一:请发布您使用的实际代码 - 第二:在您写入字节后尝试关闭客户端上的连接,因为我的猜测是,您正在使用 stream i> 不完全正确的方式
  • 我可以从代码中看出,它最有可能是海王星发射的粒子的干扰。我强烈建议您用锡箔纸保护整个城市,以获得更高质量的传输。
  • 首先:我已经解释了代码。在这个问题中我只关心两行,Network.Write from my client 和 Network.Read on my Server。其次,我正在创建一个连接并从我的客户端执行写入,然后我执行读取以从服务器获取响应。我在那里陷入僵局。
  • 你确定你的 .Read 真的“等待来自客户端的一些输入”并且不只是返回读取了 0 个字节吗?

标签: c# .net networking tcp client-server


【解决方案1】:

抛开聪明的 cmets 不谈:即使您只对 2 行代码感兴趣,我敢打赌您的问题出在代码的其他地方。

使用here 找到的代码的修改版本,我构建了一个在我的测试中有效的简单示例。

    public static void Main()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 13000.
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];

            Console.Write("Waiting for a connection... ");

            // Perform a blocking call to accept requests.
            // You could also user server.AcceptSocket() here.
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Connected!");

            // Get a stream object for reading and writing
            NetworkStream stream = client.GetStream();

            stream.Read(bytes, 0, bytes.Length);
            Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));
            // Shutdown and end connection
            client.Close();
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }

当我用另一个程序发送 1 个字节时,读取调用将等待并返回。我们需要查看一些代码来弄清楚为什么这有效而您的无效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2015-12-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    相关资源
    最近更新 更多