views:

24

answers:

3

Hi,

I am new to network programming in C#. I have found the TCPListener class very useful for sending text between computers, but 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

+2  A: 

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.

Ron Klein
+1  A: 

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.

codymanix
Instead of .NET Remoting, look into WCF.
Dave Markle
Is there a problem with .net remoting?
codymanix
A: 

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.

Guy Starbuck