0

我正在尝试通过 NetworkStream 将屏幕截图的 Base64 字符串发送到服务器,看来我正在接收完整的字符串,问题是它被打乱了......

我认为这与它被碎片化并重新组合在一起有关吗?解决这个问题的合适方法是什么......

客户代码

byte[] ImageBytes = Generics.Imaging.ImageToByte(Generics.Imaging.Get_ScreenShot_In_Bitmap());
string StreamData = "REMOTEDATA|***|" + Convert.ToBase64String(ImageBytes);
SW.WriteLine(StreamData);
SW.Flush();

服务器代码

char[] ByteData = new char[350208];
SR.Read(ByteData, 0, 350208);
string Data = new string(ByteData);
File.WriteAllText("C:\\RecievedText", Data);

发送消息的大小和 char 数组也完全一样。\

编辑: 在搞砸了一些之后,我意识到文本没有被打乱,但正确的文本落后于前一个流。我如何确保流清晰或获取整个文本

4

1 回答 1

0

您可能没有阅读所有先前的回复。您必须循环读取,直到没有数据,如下所示:

char[] ByteData = new char[350208];
int totalChars = 0;
int charsRead;
while ((charsRead = SR.Read(ByteData, totalChars, ByteData.Length - totalChars) != 0)
{
    totalChars += charsRead;
}
string Data = new string(ByteData, 0, totalChars);
File.WriteAllText("C:\\RecievedText", Data);

这里的关键是StreamReader.Read最多读取您告诉它的最大字符数。如果没有那么多可用的字符,它会读取可用的字符并返回这些字符。返回值告诉你它读取了多少。您必须继续阅读,直到获得所需的字符数,或者直到Read返回0

于 2013-05-13T21:57:30.483 回答