开发者

Send serialised object via socket

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 m开发者_JAVA百科essage'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


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.


  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.


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).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜