gpt4 book ai didi

c# - XmlSerializer.Deserialize 通过 NetworkStream block

转载 作者:行者123 更新时间:2023-11-30 12:36:42 25 4
gpt4 key购买 nike

我正在尝试通过网络流发送 XML 可序列化对象。

我已经在 UDP 广播服务器上使用过它,它从本地网络接收 UDP 消息。这是服务器端的片段:

while (mServiceStopFlag == false) {
if (mSocket.Available > 0) {
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, DiscoveryPort); byte[] bData;

// Receive discovery message
bData = mSocket.Receive(ref ipEndPoint);
// Handle discovery message
HandleDiscoveryMessage(ipEndPoint.Address, bData);
...

相反,这是客户端:

IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Broadcast, DiscoveryPort);
MemoryStream mStream = new MemoryStream();
byte[] bData;

// Create broadcast UDP server
mSocket = new UdpClient();
mSocket.EnableBroadcast = true;

// Create datagram data
foreach (NetService s in ctx.Services)
XmlHelper.SerializeClass<NetService>(mStream, s);
bData = mStream.GetBuffer();

// Notify the services
while (mServiceStopFlag == false) {
mSocket.Send(bData, (int)mStream.Length, ipEndPoint);
Thread.Sleep(DefaultServiceLatency);
}

它工作得很好。

但现在我试图获得相同的结果,但在 TcpClient 套接字上,但直接使用 XMLSerializer 实例:

在服务器端:

    TcpClient sSocket = k.Key;
ServiceContext sContext = k.Value;
Message msg = new Message();

while (sSocket.Connected == true) {
if (sSocket.Available > 0) {
StreamReader tr = new StreamReader(sSocket.GetStream());
msg = (Message)mXmlSerialize.Deserialize(tr);

// Handle message
msg = sContext.Handler(msg);
// Reply with another message
if (msg != null)
mXmlSerialize.Serialize(sSocket.GetStream(), msg);
} else
Thread.Sleep(40);
}

在客户端:

NetworkStream mSocketStream;
Message rMessage;

// Network stream
mSocketStream = mSocket.GetStream();

// Send the message
mXmlSerialize.Serialize(mSocketStream, msg);
// Receive the answer
rMessage = (Message)mXmlSerialize.Deserialize(mSocketStream);

return (rMessage);

数据已发送(可用属性大于 0),但方法 XmlSerialize.Deserialize(应反序列化 Message 类)阻塞。

我错过了什么?

最佳答案

当然是因为序列化器继续读取NetworkStream,并且在遇到主要结束元素时它并没有结束。

要获得想要的结果,有必要使用 MemoryStream,它会在读取最后一个字节时通知流结束。

关于c# - XmlSerializer.Deserialize 通过 NetworkStream block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2739653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com