filename(string)、filesize(int)、およびfile(byte [])を送信しています。何が起こっているのかというと、サーバー側でデータが処理される速度に応じて、NetworkStreamがまだ必要のないデータを読み取った場合があります。
例:.Readを実行してファイル名を取得し、filename、filesize、およびファイルの生データのデータを取得します。これは、最初の.Readがまだ実行されていないときに、サーバーが.Writeを実行し、データをストリームに書き込むために発生すると思います。これは私のファイルサイズを壊してしまいます。ファイルサイズの.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);
}
}