我们有一个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插座的等效?