Using XMLSerializer to send XML data on a NetworkStream over a socket connection



I want to send XML data from a server to some clients over a network
connection using the TCP/IP protocol. If I send the XMLs as byte
arrays I need to insert header information in the data to distinguish
the XMLs from each other in the stream of data. Is there any way to
avoid this (for instance by sending SOAP telegrams))?

I have tried using the XMLSerializer.Serialize(stream) to serialize
the XML telegrams and send them over the socket connection but when I
want to use the XMLSerializer.Deserialize(stream) to read the sent
telegrams it either newer finishes or returns a xml parse error.

//Send the XML
ShoppingList myList = new ShoppingList();
myList.AddItem(new ShoppingItem("eggs", 1.49));
myList.AddItem(new ShoppingItem("ground beef", 3.69));
myList.AddItem(new ShoppingItem("bread", 0.89));

XmlSerializer s = new XmlSerializer(typeof(ShoppingList));
stream = new NetworkStream(m_socWorker);
s.Serialize(stream, myList);

//Receive the XML
// Deserialization
ShoppingList newList;
XmlSerializer s = new XmlSerializer(typeof(ShoppingList));
newList = (ShoppingList)s.Deserialize(stream);

What am I doing wrong? Will the Deserialize() method be able to
separate the XML telegrams in the stream automatically?

Best regards,

Marc Gravell

That looks like it should work... did you close the stream after

Anyways... to investigate, the first thing I would do would be to read
the stream contents into a string (or perhaps an XmlDocument since you
am expecting xml) and double-check what we received at the client.


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question