开发者

Sending XML format messages through TCP in C#

I have a C# TCP chat program. Currently, I have formatted the messages sent using strings i.e, a "login" message starts with a "3" then followed by a "U:" then the username etc.

I think this method is very crude in a way that it's not really readable and not standardized. In early research, I have read that I can format my messages using XML but I dont know where to start exactly. Do I just mak开发者_StackOverflow中文版e a string builder and append it tags like .append("<Login>"+message)?


The most common approach for dealing with a problem like this is to use serialization. Serialization is the process of converting an in-memory object into a format that can be easily streamed "over the wire," and de-serialization is the reverse process of converting the serialized format back into an object. .NET has good support for XML and binary serialization out-of-the-box, but there are other ways to implement this. Here's a link to get you started:

http://msdn.microsoft.com/en-us/library/7ay27kt9(VS.71).aspx


You can send whatever you like over the connection - as long as it's just for your program it doesn't really matter what you choose. Xml might give you some benefits as it lends itself to some kind of more structured messages and there are many classes and tools and knowledge around on the net regarding XML. JSon format might be another option - it will make it potentially easier creating a JavaScript client for it in case you want to go web based.


Unless there is a reqirement that 3rd parties be able to read these messages then I would probably favour binary serialisation, as it has a more compact format.

That said, I'd probably just use WCF rather than uisng TCP directly.

If you want to know more about XML serialisation then the most commonly used methods are:

  • Generating a stronly typed C# object decorated with attributes to control XML serialisation using XSD.exe, and then using XmlSerializer to serialise and deserialise XML. (recommended)
  • Using the XmlDocument class

You can write our XML yourself as a string, but its better to use the serialisation methods made available in the .Net framework as it makes things considerably easier and reduces the chance that you will make a mistake and inadvertantly start working with invalid xml.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜