我正在尝试通过网络流发送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);


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

我想念什么?

最佳答案

当然,因为序列化程序继续读取NetworkStream,并且在加密主要结束元素时它不会结束。

为了获得想要的结果,必须使用MemoryStream,当读取最后一个字节时,它会通知流的结尾。

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

10-09 02:00