简体   繁体   English

TCP套接字,在单个网络流C#上发送多个对象

[英]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. 我正在尝试通过ArrayList绑定声音和图像序列数据,以使其同步并通过二进制格式化程序对其进行序列化,以通过网络流进行发送。 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). TCP是基于流的,而不是基于消息的(如UDP)。 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. TCP仅保证以正确的顺序接收所有字节。 It does not guarantee that everything sent with one Send() will be received with one Receive() . 它不保证通过一个Send()所有内容都将通过一个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. 在这种情况下,标题是Jon建议的方式。

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. 因此,您需要先解析接收到的缓冲区,然后再将任何内容发送到BinaryFormatter进行反序列化。

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. 我会将要发送的每个对象拆分为一个单独的“消息”,其中一条消息由(例如)4个字节组成,分别表示主体长度和主体本身。

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. 传入流仅用于读取消息,不用于对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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