我们有一个UWP应用程序,它有一个使用 DataReader.ReadUInt32()的监听器,我们指定我们传递的消息的长度。之前,它只是从其他使用 DataWriter.WriteUInt32()的UWP应用程序收听,因此它能够正确读取它。
现在我们正在添加与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);
.NET Socket中是否有相当于WriteUInt32()的内容?
答案 0 :(得分:2)
DataWriter类。我们可以在uwp app中使用BinaryWriter
类,它具有相同的功能和方法,例如DataWriter
。对于DataWriter.WriteUInt32
方法,BinaryWriter
具有Write(UInt32)
方法。但是如果在套接字的一侧使用BinaryWriter
,则需要使用BinaryReader
类来读取另一端,DataReader
可能无法读取正确的数据。例如,如果服务器端Write(UInt32)
,我们需要在客户端BinaryReader.ReadUInt32
。 uwp app支持BinaryWriter
和BinaryReader
。所以示例代码如下:
服务器端的作者(.Net控制台项目)
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");
}
客户端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());
}
}