.Net SslStream Write/Read issue

谁都会走 提交于 2019-12-10 15:49:00

问题


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.

Example :

Client

var message = new byte[]{1,2,3,4,5};
   sslStream.Write(messsage);
   sslStream.Flush();

Server

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 ?


回答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.

The best fix for this is to not use sockets. Use a higher level API such as WCF, SignalR, HTTP, ...

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.




回答2:


@usr is completely right about whe way stream read should be implemented, and that id you dont't expect anything. On the other side what happened to me was same happened to @Bubba. Code was, working and now it's not. Reason? Microsoft update for .net framework. More details here: https://connect.microsoft.com/VisualStudio/feedback/details/2590316/windows-10-update-kb3147458-changes-behavior-of-sslstream-read-beginread-endread




回答3:


I am experiencing the same problem. The code was working several weeks ago - now it's not working. I wonder if one of the Microsoft updates broke it?

I created a work around (hack) - until I can figure out what the problem is: (at the class level)

string previousChar = null;

(in the callback function for TcpClient.GetStream.Begin)

        if ((previousChar == null) && (bytesRead == 1))
        {
            previousChar = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
        }
        // Convert the byte array the message was saved into
        if (bytesRead > 6)
        {
            message = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
            if (previousChar != null)
            {
                message = previousChar + message;
                previousChar = null;
            }


来源:https://stackoverflow.com/questions/37053288/net-sslstream-write-read-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!