C#流套接字,如何分离的消息? [英] C# streaming sockets, how to separate messages?

查看:120
本文介绍了C#流套接字,如何分离的消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还挺长的头衔,但反正...

Kinda long title, but anyways...

我一直在寻找在这些例子中,特别是在写作部分和阅读邮件的大小字节流

的http://文档。 trolltech.com/4.4/network-fortuneclient-client-cpp.html

http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html

I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams
http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html
http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html

但我似乎无法弄清楚在C#

But I can't seem to figure it out in C#.

StreamWriter writer = new StreamWriter(tcpClient.GetStream());
writer.Write(data.Length + data);

这根本不​​能很好地工作。可能有人给我一个正确的方向轻推?

This doesn't work very well at all. Could someone give me a nudge in the right direction?

推荐答案

通常你会先发送的长度。

Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary:

  byte[] data = ...
  int len = data.Length;
  byte[] prefix = Bitconverter.GetBytes(len);
  stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes
  stream.Write(data, 0, data.Length);



显然,调用者需要做同样的 - 即读出前4个字节来获取长度。对于阅读,接收方应注意不要过分解读数据。一种方式是使用一个限制流 - 例如,的这个类可以用来获取流不会过分解读。

Obviously the caller needs to do the same - i.e. read the first 4 bytes to get the length. For reading, the receiver should take care not to read too much data. One way is with a limiting stream - for example, this class can be used to get a Stream that won't read too much.

如果你不想总是发送4架空字节,那么一些更有趣的编码是可能的 - 例如,使用最高位作为一个延续块

If you don't want the overhead of always sending 4 bytes, then some more interesting encodings are possible - for example, using the msb as a continuation block.

有关信息,的 protobuf网是一个二进制序列围绕谷歌的设计的协议缓冲区基于消息的格式。它可以处理大量的细节你,也许会感兴趣,如果你不想花费大量的时间编写序列化代码。有例子在快速启动项目插座,的例如这里

For info, protobuf-net is a binary serializer designed around Google's "protocol buffers" message-based format. It handles a lot of the details for you, and might be of interest if you don't want to spend lots of time writing serialization code. There are examples for sockets in the QuickStart project, for example here

这篇关于C#流套接字,如何分离的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆