我正在发送一个文件名(字符串)、文件大小(int)和文件(字节[])。正在发生的事情是,在某些情况下,根据服务器端处理数据的速度,NetworkStream 已经读取了我还不需要的数据。
示例:我执行 .Read 来获取文件名,我将获取文件名、文件大小和文件原始数据的数据。我认为发生这种情况是因为服务器只是执行 .Write 并将数据写入流中,而第一个 .Read 尚未执行。这最终破坏了我的文件大小.Read。现在,当我为我的文件大小执行 .Read 时,我显示了一个巨大的数字,当我去读取文件本身并根据读取的文件大小分配一个新的 byte[] 时,我得到了 OutOfMemory 异常。
如何正确同步读取?我在网上找到的例子就是按照我的方式做的。
一些代码:
private void ReadandSaveFileFromServer(TcpClient clientATF, NetworkStream currentStream, string locationToSave)
{
int fileSize = 0;
string fileName = "";
int readPos = 0;
int bytesRead = -1;
fileName = ReadStringFromServer(clientATF, currentStream);
fileSize = ReadIntFromServer(clientATF, currentStream);
byte[] fileSent = new byte[fileSize];
while (bytesRead != 0)
{
if (currentStream.CanRead && clientATF.Connected)
{
bytesRead = currentStream.Read(fileSent, readPos, fileSent.Length);
readPos += bytesRead;
if (readPos == bytesRead)
{
break;
}
}
else
{
WriteToConsole("Log Transfer Failed");
break;
}
}
WriteToConsole("Log Recieved");
File.WriteAllBytes(locationToSave + "\\" + fileName, fileSent);
}
private string ReadStringFromServer(TcpClient clientATF, NetworkStream currentStream)
{
int i = -1;
string builtString = "";
byte[] stringFromClient = new byte[256];
if (clientATF.Connected && currentStream.CanRead)
{
i = currentStream.Read(stringFromClient, 0, stringFromClient.Length);
builtString = System.Text.Encoding.ASCII.GetString(stringFromClient, 0, i);
}
else
{
return "Connection Error";
}
return builtString;
}
private int ReadIntFromServer(TcpClient clientATF, NetworkStream currentStream)
{
int i = -1 ;
int builtInteger = 0;
byte[] integerFromClient = new byte[256];
int offset = 0;
if (clientATF.Connected && currentStream.CanRead)
{
i = currentStream.Read(integerFromClient, offset, integerFromClient.Length);
builtInteger = BitConverter.ToInt32(integerFromClient, 0);
}
else
{
return -1;
}
return builtInteger;
}
我试过使用偏移量......没有运气。感谢您的帮助。
我开始了另一个问题,但它与其他问题有关。
提前感谢肖恩
编辑:这是我的发送字符串代码:
private void SendToClient( TcpClient clientATF, NetworkStream currentStream, string messageToSend)
{
byte[] messageAsByteArray = new byte[256];
messageAsByteArray = Encoding.ASCII.GetBytes(messageToSend);
if (clientATF.Connected && currentStream.CanWrite)
{
//send the string to the client
currentStream.Write(messageAsByteArray, 0, messageAsByteArray.Length);
}
}