2

I'm trying to pass a custom class from one tcp client to another (using TcpListener, TcpClient and XmlSerializer).

I got 1 problem that breaks into 2 problems.

when i'm using this code, the client hangs while Serilization is being done (i think the other side doesnt know when the data is fully sent):

public void SendData(myMessage messageClass)
{
    NetworkStream serverStream = tcpServer.GetStream();
    XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
    xmlSrlz.Serialize(serverStream, messageClass);
    serverStream.Flush();
}

public myMessage ReadData()
{
    while (true)
    {
        NetworkStream clientStream = client.GetStream();
        XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
        int bytesToread;
        byte[] inStream = new byte[10025];
        myMessage msg;
        do
        {
            msg = (myMessage)xmlSrlz.Deserialize(clientStream);
            clientStream.Flush();
        }
        while (((bytesToread = clientStream.Read(inStream, 0, (int)client.ReceiveBufferSize)) > 0));
        return msg;
    }
}

So, when i searched around i noticed i can dispose the stream (or use using) and that way let the other side know that the Data has fully sent and theres no more Data to send:

public void SendData(myMessage messageClass)
{
    using (NetworkStream serverStream = tcpServer.GetStream())
    {
        XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));
        xmlSrlz.Serialize(serverStream, messageClass);
        serverStream.Flush();
    }
}

public myMessage ReadData()
{
    while (true)
    {
        using (NetworkStream clientStream = client.GetStream())
        {
            XmlSerializer xmlSrlz = new XmlSerializer(typeof(myMessage));

            int bytesToread;
            byte[] inStream = new byte[10025];
            myMessage msg;
            do
            {
                msg = (myMessage)xmlSrlz.Deserialize(clientStream);
                clientStream.Flush();
            }
            while (((bytesToread = clientStream.Read(inStream, 0, (int)client.ReceiveBufferSize)) > 0));
            return msg;
        }
    }
}

But now i lost the connection of them 2 clients.

when i'm trying to send another Message i get the exception:

The operation is not allowed on non-connected sockets.

So how can i send the Serilized object without breaking the connection?

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99

1 Answers1

1

First off, using a using like that is closing your socket by disposing the underlying stream. Bad idea.

Second, consider serializing to and from a string, instead of serializing directly into the stream. I'm not sure if there are side-effects of doing that, but there certainly could be.

You can use this question to serialize/deserialize from string: Deserialize from string instead TextReader

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117