Taufiq Abdur Rahman
Taufiq Abdur Rahman

Reputation: 1388

Socket Programming Exception There is an error in XML document (170, 46)

I want to send a list of objects through a socket connection. And i know WCF service would be a better option but its not a option for me.

I am using this code to send the data

    private void tm_Tick(object sender, EventArgs e)
    {

        XmlSerializer formatter = new XmlSerializer(typeof(List<Objects.PIP>));

        MemoryStream stream = new MemoryStream(1024);

        formatter.Serialize(stream, Repository.GlobalRepository.PIPInformation);

        byte[] bt = stream.ToArray();
        foreach (Communication.Client Client in server.ClientList)
        {
            Client.SendMessage(bt);

        }
        stream.Flush();
    }

    public void SendMessage(Byte[] bytesSent)
    {
        SocketAsyncEventArgs writeEventArgs = new SocketAsyncEventArgs();
        writeEventArgs.SetBuffer(bytesSent, 0, bytesSent.Length);
        socket.SendAsync(writeEventArgs);
    }

Seems to work fine.

to receive data i am using this code on a thread.

void ReceiveData()
    {
        try
        {

            while (true)
            {
                if (disposed == true)
                    return;
                data = new byte[socket.ReceiveBufferSize];
                var recv = socket.Receive(data);

                XmlSerializer formatter = new XmlSerializer(typeof(List<Object.PIP>));
                MemoryStream stream = new MemoryStream(data);
                **Classes.TickerInformation.PIPList= (List<Object.PIP>)formatter.Deserialize(stream);**

            }
            socket.Close();
            return;
        }
        catch (Exception ex)
        {

        }

    }

i am getting an Exception There is an error in XML document (170, 46). in this line: Classes.TickerInformation.PIPList= (List)formatter.Deserialize(stream);

I assume the all the data is not being recieved so this is happening.

Upvotes: 0

Views: 325

Answers (1)

Aliostad
Aliostad

Reputation: 81690

The problem is you have not received the whole of the XML till the end - so you are serialising only the initial part of the XML. You have to read from the socket until there is no data.

I suggest to setup a terminator string sent by the client so you look for it to know you have fully received the message.

Bear in mind, sockets are not based on request-response. you open the socket and keep reading.

Upvotes: 2

Related Questions