XmlSerializer.Deserialize blocks over NetworkStrea

2019-02-18 16:06发布

问题:

I'm trying to sends XML serializable objects over a network stream.

I've already used this on an UDP broadcast server, where it receive UDP messages from the local network. Here a snippet of the server side:

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);
    ...

Instead this is the client side:

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);
}

It works very fine.

But now i'me trying to get the same result, but on a TcpClient socket, but the using directly an XMLSerializer instance:

On server side:

    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);
}

And on client side:

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);

The data is sent (Available property is greater than 0), but the method XmlSerialize.Deserialize (which should deserialize the Message class) blocks.

What am I missing?

回答1:

Of course because the serializer continue to read the NetworkStream, and it doesn't ends when encouter the main end element.

To achieve the wanted result it's necessary the use of a MemoryStream, which notify the end of stream when the last byte was read.