XML messages over a TCP/IP socket
I am using C and want to know are XML messages are preferable over text messages as far as 开发者_开发百科communication over a socket connection is concerned?
- Is there any other good option available rather to go for XML?
- Which is the best parser(or parsing option) available for parsing XML in C?
- Is there any standard library which comes with C and helps to parse XML messages?
You design the protocol so you decide. You can use text or binary communication. Whatever format you use, you decide the how to serialize/de-serialize and interpret data. If you use XML, you can leverage on XMLRPC or SOAP. You can use JSONRPC as well. Last time in my project, I used binary in a very simple yet efficient way: The first to identify the method/function to call. The next 2 bytes to inform the length of data (up to 64K - 1 bytes) and the rest is data. Take note of Big/Small Endianess.
It's very subjective. You could use validating or non-validating parsers. TinyXML is lightweight one. You can look into MiniXML and Expat. libxml2 is fatter.
So far XML parsing is not in standard libraries of C or C++. You could use the aforementioned libraries.
Good luck!
EDIT:
By the way, if you want to use binary format to exchange data, just use any of these 3:
http://tpl.sourceforge.net/ - C serialization library.
http://www.s11n.net/c11n/ - A powerful and complicated C serialization library.
Siseria - http://sourceforge.net/projects/siseria/ , purely in C. I wrote for an embedded system project. It runs without any dependency and is very fast! Compared to other 2, mine is very simple and does not use heap and dynamic memory at all. Everything is on the stack!
There are any number of possible solutions. I would look at a few other options before picking XML, I think. XML has quite a lot of overhead; unless you're going to compress your streams it might be a bit costly. XML also isn't easy to edit for humans, although of course more so than a binary format.
You might want to look at JSON, it's a very popular format and is far simpler than XML. There are plenty of implementations available.
I can highly recommend Protobuf, Google's data interchange format. We're using it for communicating between two processes, at it works great. It has built-in support for C++, Python, and Java, and 3-rd party libraries for a bunch of others (Jon Skeet maintains the C# port).
The main question is what are your performance requirements.
If you are going to send one message per second, feel free. If you have human interface on one end, use XML or any other text format.
If you design a machine-to-machine interface, you'd rather consider binary data. Remember to convert everything to network-standard byte order in this case.
精彩评论