C# passing objects TCPListener
I am new to network programming in C#. I have found the TCPListener class very useful for sending text between computers, b开发者_StackOverflow社区ut I was wondering if it is possible to directly send objects (assuming both client and server have the class definition) between machines without having to first convert them to string and then make an object with that data.
Thanks,
PM
One solution for your issue is using WCF and mark your objects as Serializable
, with TCP binding. But that's quite a different approach than the "low-level", socket based solution you already have. However, I'd give WCF a try.
You cannot send "objects" directly through the network. You have to either convert them into a parseable binary or text form. For the latter, xml is best suited often. You can use BinaryFormatter
or XmlSerializer
for this.
If you really want to send .NET objects, because you only serve .net clients, tcp may be to low level for your needs. In this case have a look at .net remoting which allows you to directly exchange objects betwen server and client.
As long as the class definitions are the same on both sides, you can use binary serialization to serialize any object to a stream:
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
You are better off using WCF as noted above, though, since this will break if the assemblies are versioned on either side of the wire.
精彩评论