2017-04-22 74 views
0

在我的項目中,我使用StreamSocket發送文件和StreamSocketListener接收LAN中的文件。但是,當我測試時,我收到的文件大小小於我發送的文件(例如,我發送的文件大小約爲100M,收到的文件大小隻有2-3M)使用StreamSocket傳輸文件和接收錯誤數據(UWP)

我非常困惑,這裏是我的代碼,tks。

發送代碼(文件StorageFile,項目是我的自定義類)

var fileStream = await file.OpenStreamForReadAsync(); 
var fileInputStream = fileStream.AsInputStream(); 

StreamSocket socket = new StreamSocket(); 
HostName serverHost = new HostName(item.Address); 
string serverPort = item.Port; 
await socket.ConnectAsync(serverHost, serverPort); 

uint capacity = 10000000; 
Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity); 

// Send some heads 
StreamWriter streamWriter = new StreamWriter(socket.OutputStream.AsStreamForWrite()); 
await streamWriter.WriteLineAsync("file"); 
await streamWriter.WriteLineAsync(file.Name); 
await streamWriter.FlushAsync(); 

var outputStream = socket.OutputStream; 

while (true) 
{ 
    await fileInputStream.ReadAsync(buffer, capacity, InputStreamOptions.None); 

    if (buffer.Length > 0) 
    { 
     await outputStream.WriteAsync(buffer); 
     await outputStream.FlushAsync(); 
    } 
    else 
    { 
     break; 
    } 
} 

streamWriter.Dispose(); 
outputStream.Dispose(); 
socket.Dispose(); 

接收代碼(事件是StreamSocketListener.ConnectionReceived

StreamReader streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()); 
string head = await streamReader.ReadLineAsync(); 

string fileName = await streamReader.ReadLineAsync(); 

StorageFile file = await DownloadsFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); 
var inputStream = args.Socket.InputStream; 

uint capacity = 10000000; 
Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity); 

if (file != null) 
{ 
    CachedFileManager.DeferUpdates(file); 

    while (true) 
    { 
     await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None); 

     if (buffer.Length > 0) 
     { 
      await FileIO.WriteBufferAsync(file, buffer); 
     } 
     else 
     { 
      break; 
     } 
    } 

    FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(file); 
} 
+0

您應該檢查ReadAsync方法的返回值,而不是檢查buffer.Length。 –

回答

0

我剛纔解決了這個問題。在接收代碼中,我使用等待FileIO.WriteBufferAsync(文件,緩衝區);將緩衝區寫入文件。此方法不能將緩衝區追加到文件。所以我使用OutputStream.WriteAsync()來處理它。