2016-11-28 80 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"); 
    } 

读写器