问题描述
当我阅读一个.Net SSLStream时,似乎无法一次阅读所有内容. read方法始终仅获取第一个字节.无论数据或缓冲区大小如何,我都需要循环获取剩余的数据.
When I read an a .Net SSLStream, I can't seem to read it all in one go. The read method always gets the first byte only. I need to loop to get the remaining data no matter the data or buffer size.
示例:
客户
var message = new byte[]{1,2,3,4,5};
sslStream.Write(messsage);
sslStream.Flush();
服务器
byte[] buffer = new byte[4000];
bytes = sslStream.Read(buffer, 0, buffer.Length);
我做错什么了吗?为什么在第一次读取时只读取一个字节?
Am I doing something wrong ? Why is it reading only one byte on the first read ?
推荐答案
流API不会保证您每次读取都返回特定数量的字节.您可以读取从1开始的任意数量的字节.即使我们请求更大的块,甚至发送了更大的块,我们的代码也必须能够按字节接收数据.
Streaming APIs do not promise you to return a specific number of bytes per read. You can read any number of bytes starting from 1. YOur code must be able to deal with receiving the data byte-wise even if you asked for bigger chunks and even if you sent bigger chunks.
对此的最佳解决方法是不使用套接字.使用更高级别的API,例如WCF,SignalR,HTTP,...
The best fix for this is to not use sockets. Use a higher level API such as WCF, SignalR, HTTP, ...
如果您坚持要使用BinaryReader/Writer
来发送数据.这很容易.
If you insist you probably should use BinaryReader/Writer
to send your data. That makes it quite easy.
如果您不想要其中的任何一个,则需要循环读取,直到收到所需的字节数为止.
If you don't want any of that you need to read in a loop until you have received as many bytes as you need.
这篇关于.Net SslStream写入/读取问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!