2012-08-01 91 views
1

我正在使用Windows 8 Metro App中的StreamSockets並希望使用DataReader讀取傳入數據。是否有任何特定的模式或模型可用於從套接字中讀取數據,以便隨時讀取網絡緩衝區中可用的所有數據?Metro中的StreamSocket讀取

目前,我明白我需要調用DataReader.LoadAsync(),然後DataReader.Read ...()。我希望能夠隨時讀取當前網絡緩衝區中的所有內容。當我想要檢測傳入消息的結尾時出現問題。如果我嘗試使用一個循環來連續調用LoadAsync,它會在到達網絡緩衝區的末尾時進行阻塞。我知道在.NET 4.0中,有一個NetworkStream類提供了一個DataAvailable字段,告訴我網絡緩衝區中是否存在任何數據,這樣我可以繼續循環,直到該標誌爲false。有沒有什麼辦法可以做類似的事情,使我可以消耗網絡緩衝區中的所有數據,而不必長時間阻塞?

回答

0

Set DataReader.InputStreamOptions = InputStreamOptions.Partial。這將使您的等待(您的任務)在您提供的緩衝區完全填滿之前返回。

using(DataReader inputStream = new DataReader(this.connection.InputStream)) 
{ 
    inputStream.InputStreamOptions = InputStreamOptions.Partial; 
    DataReaderLoadOperation loadOperation = inputStream.LoadAsync(2500); 
    await loadOperation; 
    if(loadOperation.Status != AsyncStatus.Completed) 
    { 
     this.Disconnect(); //insert your handler here 
     return; 
    } 

    //read complete message 
    uint byteCount = inputStream.UnconsumedBufferLength; 

    byte [] bytes = new byte[byteCount]; 
    inputStream.ReadBytes(bytes); 

    this.handleServerMessage(bytes); //insert your handler here 

    //detach stream so that it won't be closed when the datareader is disposed later 
    inputStream.DetachStream();     
} 
相關問題