2012-08-01 39 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();     
} 
相关问题