clientStream.Read返回错误的字节数 [英] clientStream.Read returns wrong number of bytes
问题描述
此代码有效:
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[5242880];
int bytesRead;
bytesRead = clientStream.Read(message, 0, 909699);
但这会返回错误的字节数:
But this returns the wrong number of bytes:
bytesRead = clientStream.Read(message, 0, 5242880);
为什么?我该如何解决?
Why? How can I fix it?
(实际数据大小为1475186;代码返回11043作为字节数)
(the real data size is 1475186; the code returns the 11043 as the number of bytes)
推荐答案
如果这是基于TCP的流,那么答案是其余数据根本还没有到达.
If this is a TCP based stream, then the answer is that the rest of the data simply didn't arrive yet.
TCP是面向流的.这意味着 Send
/ Write
调用的数量与接收事件的数量之间没有关系.可以将多个写操作组合在一起,并且可以将单个写操作拆分.
TCP is stream oriented. That means there is no relation between the number of Send
/Write
calls, and the number of receive events. Multiple writes can be combined together, and single writes can be split.
如果要在TCP上使用消息,则需要在其之上实现自己的打包算法.实现这一目标的典型策略是:
If you want to work with messages on TCP, you need to implement your own packeting algorithm on top of it. Typical strategies to achieve this are:
- 按长度打包每个前缀,通常使用二进制数据
- 使用分隔符,例如换行符.通常与文本数据一起使用.
如果要以阻塞方式读取所有数据,则可以使用循环,直到 DataAvailable
为 true
,但随后对 Read
的调用返回 0
.(希望我没记错,已经有一段时间没有进行任何网络编程了.)
If you want to read all data in a blocking way you can use loop until DataAvailable
is true
but a subsequent call to Read
returns 0
. (Hope I remembered that part correctly, haven't done any network programming in a while)
这篇关于clientStream.Read返回错误的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!