The TCP/IP communication requires a lot of processing of incoming and outgoing data. The XML communication library uses XML streams to transfer data between the TCP/IP connections. The main idea is to use predefined communication objects. These communication objects can be serialized into XML streams. This XML stream, with a very small header to identify the serialized object and the XML size, can be used to communicate.
XML communication library uses a straight forward idea:
- Define objects for each XML message wanted to be transferred.
- Serialize created object into XML stream.
- Determine the size of the generated XML stream.
- Construct communication header. I used a very simple header with the following format:
CommandID:XML Stream Size:XML Stream String
- Write the constructed header/XML data to the network stream.
- Analyze incoming data for appropriate header (command ID, and XML data size)
- Use the header to read and deserialize into the appropriate object. This can be determined using the command ID.
This mechanism makes the communication more easier and more clear to code.
Using the code
The XML communication library is mainly based on one static class' operations. This class is called
CommProtocol. This class defines a private default constructor to prevent any creation of objects for this class. This class has four static functions:
Read: Reads data from network stream.
Write: Writes data to network stream.
ReadHeader: Reads incoming header from network stream. This function is used mainly by the
ReadCommand: Deserialize the incoming XML stream to its appropriate object using the header information. This function is also mainly used by the
The following code describes how we can write to network stream using the
Write function will take care of object serialization and header building, and writing to the network stream.
The following code describes how we can read from the network stream using the
object o = CommProtocol.Read(Networkstream,out cmd);
Read function will throw an exception if the network stream is closed or header is corrupted.
The XML serialized objects are defined in the library main file CommLib.cs. For the article code, I defined one class called
CommSendText and one communication command called
I developed the communication library mainly to help myself in the development of a server based chat application. The main issue I considered when I developed this library was to make the communication that simple. For this, I used double handshaking between the server and the clients. This means, each command sent to the server must return a status to the client. This makes the communication more reliable and up to date.
There are many enhancements I want to add to this library, so your feedback is very important to me.