简体   繁体   中英

TCP sockets,Sending Multiple objects on Single Network stream C#

I am trying to bind Sound and Image Sequence Data through ArrayList in order to get it synchronized and serializing it through Binary formatter to be send over Network stream. The Server end threw an exception:

THE STREAM CAN NOT SUPPORT SEEK OPERATION.

What should I have to do in order to sync Objects to be sent over a single Network stream Instance

TCP is stream based and not message based (as UDP is). That means that there is no telling when a message starts or ends. TCP only guarantees that all bytes are received and in the correct order. It does not guarantee that everything sent with one Send() will be received with one Receive() .

Hence you need to specify some kind of message identification mechanism. In this case, a header is the way to go as Jon suggested.

However, you need to understand that the entire header might not be received at once. And that two messages might arrive at once. So you need to parse the received buffer before sending anything to the BinaryFormatter for deserialization.

I would split each object you want to send out into a separate "message" where a message consists of (say) 4 bytes indicating the body length, and then the body itself.

When you want to send a serialized object, you serialize to a byte array, write out the length, then write out the data.

At the server side, you read the length, read that much data into a byte array, then deserialize from that message. The incoming stream is only used to read messages, not objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM