views:

174

answers:

3

Whats the best way to format a message to a server, at moment I'm serilising an object using the binaryformatter and then sending it to the server.

At the server end its listening in an async fashion and then when the buffer size recieved is not 100% it assumes that the transfer has complete.

This is working and the moment, and I can deserialise the object at the other end, I'm just concerned that if I start sending async this method will fail has message's could be blurred.

I know that I need to mark the message somehow as to say that's the end of message one, this other bit belongs to message 2, but I'm unsure of the correct way to do this.

Could anyone point me in the right direction and maybe give me some examples?

Thanks

A: 
  1. If your object has a fixed length you can received specified amount of bytes on the other end and then create your object.
  2. Otherwise you can send delimiters (symbol or sequence of symbols that you are not using in your object) between your objects and keep reading received data byte by byte until you see the delimiter.
negative
The object isn't fixed length I can't use option 1, as for option to because it's going through the binary formatter I wasn't sure what would be a safe delimiter.
RubbleFord
A: 

You might want to take a look at Protocol Buffers (http://code.google.com/p/protobuf), a (implementation language independent) data interchange format/framework. There exist at least two .NET implementations for it (see http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns).

Frank Grimm
+1  A: 

You could always serialize it to a memory stream, see how big it is, send the length as a 4-byte binary number then send the stream's contents.

On the other side you can just sit and wait for 4 bytes, combine them into an integer then sit and wait for that number of bytes.

When your read function returns (make them blocking reads), you know you have the entire object into a buffer, so you just deserialize it and cast it to your common interface type.

edit: this is the answer to your specific question. This being said you would be better off using a higher-level library than pure tcp.

Blindy
The reason i'm using a socket is because there's a requirement to detect when a client has disconnected.
RubbleFord
In that case send the "packet" size before sending the packet, that always simplifies things a lot. Chances are you won't even feel it, what's 4 bytes to however big your objects are?
Blindy