【发布时间】:2020-02-07 17:14:38
【问题描述】:
我有一个模拟视频流的 exe。我连接到它并偶尔读取预期的数据,但通常我只得到前 28 个字节,然后是 65508 个字节的零。假设视频流正常工作。
TcpClient tcpClient = new TcpClient ();
int port = 13000;
myIP = IPAddress.Loopback.ToString();
tcpClient.Connect (myIP, port);
NetworkStream netStream = tcpClient.GetStream ();
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);
string dataString = Encoding.ASCII.GetString (bytes);
Console.WriteLine("\ndataString: "+dataString.Substring(0,1000));
Console.WriteLine("\nnumber of bytes read: "+bytes.Length);
tcpClient.Close ();
// Closing the tcpClient instance does not close the network stream.
netStream.Close();
我怎样才能做到每次都能得到预期的输出?
【问题讨论】:
-
您的代码不正确。应该是
var readCount = netStream.Read(bytes, 0, bytes.Length); […] Console.WriteLine("Number of bytes read: “ + readCount);。另外为什么要将二进制数据转换为文本字符串?在您显示的代码中,您从哪里获得 28 和 65508 号码? -
扩展ckun的评论:
NetworkStream.Read返回读取的字节数。超出此范围的缓冲区 (bytes) 中的任何内容都不适合消费。 TCP 只保证发送的字节按顺序到达,不重复。不能保证,例如,发送的 64 个字节不会以 3 个一组的形式到达,并且在最后一次读取时不会到达一个字节。 -
ckuri - 我将其转换为字符串,以便将其打印到控制台。我需要操作二进制文件,我认为它可以帮助我想象我需要做什么。
标签: c# tcpclient networkstream