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