C# Networkstream 什么都不读 [英] C# Networkstream reads nothing

查看:41
本文介绍了C# Networkstream 什么都不读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是尝试使用 Networkstream,这是我写的一个简单代码:

Just trying to use Networkstream, and this is a simple code i wrote:

客户端:

       TcpClient c = new TcpClient();
        c.Connect("10.0.0.4", 10);
       NetworkStream ns = c.GetStream();
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes("first");
        byte[] buffer2 = System.Text.Encoding.UTF8.GetBytes("second");
        MemoryStream stream = new MemoryStream();
       stream.Write(buffer, 0, buffer.Length);
        stream.Write(buffer2, 0, buffer2.Length);
        stream.CopyTo(ns);

这是服务器端:

        TcpListener tl = new TcpListener(IPAddress.Any, 10);
        tl.Start();
        TcpClient c = tl.AcceptTcpClient();
        NetworkStream   ns = new NetworkStream(c.Client);
        byte[] buff = new byte[5];
        ns.Read(buff,0,buff.Length);
        string result = System.Text.Encoding.UTF8.GetString(buff);
        MessageBox.Show(result);

只有当我关闭整个应用程序时,MessageBox 行才会被执行,我总是得到一个空白的消息框!这意味着 result 不包含任何内容...有什么帮助吗?

only when i close the entire application the MessageBox line is executed , and im always getting a blank messagebox! which mean result doesnt contain nothing... Any help?

推荐答案

在客户端 stream 位于流的最末端.因此,CopyTo 没有什么可以复制的了.

On the client stream is positioned at the very end of the stream. Therefore, CopyTo has nothing left to copy.

在复制前使用stream.Position = 0;.

此外,您似乎没有意识到套接字读取(实际上是任何流读取)返回的字节数可能少于请求的字节数(至少一个).您的阅读代码必须考虑到这一点.TCP 不保留消息边界.

Also, you don't seem to be aware of the fact that socket reads (in fact any stream read) can return less bytes than were requested (at least one). Your reading code must account for that. TCP does not preserve message boundaries.

这篇关于C# Networkstream 什么都不读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆