2016-11-28 53 views
0

我們有一個UWP應用程序,它有一個Listener,它使用DataReader.ReadUInt32()其中我們指定我們傳遞的消息的長度。之前,它只能從使用DataWriter.WriteUInt32()的其他UWP應用程序偵聽,因此它能夠正確讀取它。.NET Socket中的DataWriter.WriteUInt32等價物?

現在我們添加與UWP應用程序通信的.NET應用程序。問題是,.NET中的Socket似乎沒有WriteUInt32()方法的等價物。所以會發生什麼,ReadUInt32()似乎輸出不正確的數據(例如825373492)。

下面是我們的發送器和監聽器的代碼片段:

發件人:

  using (var socket = new StreamSocket()) 
      { 
       var cts = new CancellationTokenSource(); 
       cts.CancelAfter(5000); 
       await socket.ConnectAsync(hostName, peerSplit[1]).AsTask(cts.Token); 

       var writer = new DataWriter(socket.OutputStream); 
       if (includeSize) writer.WriteUInt32(writer.MeasureString(message)); 
       writer.WriteString(message); 
       await writer.StoreAsync(); 
       writer.DetachStream(); 
       writer.Dispose(); 
      } 

監聽器:

   // Read first 4 bytes (length of the subsequent string). 
       var sizeFieldCount = await reader.LoadAsync(sizeof(uint)); 
       if (sizeFieldCount != sizeof(uint)) 
       { 
        // The underlying socket was closed before we were able to read the whole data. 
        reader.DetachStream(); 
        return; 
       } 
       // Read the string. 
       var stringLength = reader.ReadUInt32(); 
       var actualStringLength = await reader.LoadAsync(stringLength); 
       if (stringLength != actualStringLength) 
       { 
        // The underlying socket was closed before we were able to read the whole data. 
        return; 
       } 

       var message = reader.ReadString(actualStringLength); 

有WriteUInt32()在.NET插座的等效?

回答

1

DataWriter類在控制檯等.NET項目中不受支持。我們可以在uwp應用中使用BinaryWriter類,它具有和DataWriter一樣的功能和方法。對於DataWriter.WriteUInt32方法,BinaryWriterWrite(UInt32)方法。但是如果在插座的一側使用BinaryWriter,則需要使用BinaryReader類來讀取另一側,DataReader可能無法讀取正確的數據。例如,如果服務器端爲Write(UInt32),我們需要在客戶端上BinaryReader.ReadUInt32。在uwp應用程序中支持BinaryWriterBinaryReader。因此,示例代碼如下:

在服務器端(.NET控制檯項目)在客戶端的sode(UWP APP)

using (BinaryReader reader = new BinaryReader(socket.InputStream.AsStreamForRead())) 
{     
    try 
    {  
     var stringLength = reader.ReadUInt32(); 
     var stringtext= reader.ReadString(); 

    } 
    catch (Exception e) 
    { 
     return (e.ToString()); 
    } 
} 

Socket socket = myList.AcceptSocket(); 
    NetworkStream output = new NetworkStream(socket); 
    using (BinaryWriter binarywriter = new BinaryWriter(output)) 
    { 
     UInt32 testuint = 28; 
     binarywriter.Write(testuint); 
     binarywriter.Write("Server Say Hello"); 
    } 

讀寫器