我正在使用以下代碼通過tcp發送文件。.NET中的TCP文件發送問題,NetworkStream Socket
如果我連續發送多次相同的文件來測試它是否健壯,我會正確接收第一個文件,而另一個則搞砸了。
所有搞砸的文件有相同的不正確的字節,如果我睡覺(一段時間)所有文件傳輸正確。我發現我必須在讀取我的文件時實例化一個新的緩衝區,以便正確地完成一切。但我不明白爲什麼。
我擔心我重新實現緩衝區的解決方案可能只是隱藏了另一個主要問題。任何建議?
using(var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(var binaryReader = new BinaryReader(fileStream))
{
var _sendingBuffer = new byte[BUFFER_SIZE];
int length = (int)fileStream.Length;
int bytesRead = 0;
//Ensure we reached the end of the stream regardless of encoding
while (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
{
bytesRead = binaryReader.Read(_sendingBuffer, 0, _sendingBuffer.Length);
_socket.BeginSend(_sendingBuffer, 0, bytesRead, SocketFlags.None, SendFileCallback, null);
//without this i received some messed up data
_sendingBuffer = new byte[BUFFER_SIZE];
}
}
}
發送的部分是每答案錯誤。也許接收部分也壞了。發佈代碼。 – usr
請注意,依靠像HTTP這樣的標準協議更容易。套接字非常難以使用。 – usr
其實發送和接收部分正在工作,我沒有尋找一種方法來完成這個東西。我無法使用Http我受許多方面的環境,需求和策略的限制(WinCE) – sam