我設法通過TCP使用NetworkStream
和套接字發送二進制數據。 我唯一的問題是,當我發送較大的文件,如幾百KB的圖像,他們沒有得到正確的傳輸,圖像的一半丟失。在服務器端I Socket.Send
傳輸數據。在客戶端,我使用Socket.BeginReceive
和1024
大小的緩衝區,將其寫入MemoryStream
,稍後使用new Bitmap(Stream)
將該MemoryStream
轉換爲可在PictureBox
中顯示的圖像。C#通過互聯網發送文件
我應該使用什麼方法來避免數據丟失?
編輯:代碼發佈
listener = new TcpListener(myAddress, 86);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
ns = client.GetStream();
byte[] buffer = new byte[1024];
while (fileTransfer)
{
ms = new MemoryStream();
do
{
int length = ns.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, length);
// with this line added the data loss apparently disappears
System.Threading.Thread.Sleep(1);
} while (ns.DataAvailable);
UpdateData();
ms.Dispose();
System.Threading.Thread.Sleep(10);
}
ns.Dispose();
client.Close();
listener.Stop();
編輯:數據仍然是腐敗有時甚至與睡眠方法。
請發佈您的代碼,以便發現錯誤。 – Oded
發佈您的代碼。如果沒有,我們只是猜測。 – ChrisF
這看起來沒問題,所以假設它不是網絡問題,在發送方或接收方都有問題,我們需要查看該代碼。 – nos