简体   繁体   English

C#使用TCP流发送数据包

[英]C# Packet sending using TCP streams

I'm trying to send multiple packets from a tcp server to a client using only read and write from the base "Stream" class. 我正在尝试使用来自基本“Stream”类的读写来从tcp服务器向客户端发送多个数据包。 The problem is, I don't know what the size of the packet will be (client side). 问题是,我不知道数据包的大小(客户端)。 Should I send and int (4 bytes) before each packet so the client can ajust the buffer and receive only the nuber of bytes specified? 我应该在每个数据包之前发送和int(4个字节),以便客户端可以调整缓冲区并仅接收指定的nuber字节吗? I feel like there's already something in the tcp protocol that handles that but I can't seem to find it. 我觉得tcp协议中已有一些东西可以处理,但我似乎无法找到它。

The process for what you are wanting to do is called Message Framing and there is no built in mecinism in TcpClient that does this for you. 您想要做的事情的过程称为消息框架,并且TcpClient中没有为您做到这一点的内置机制。 It is the responsibility of the higher level application layer to do it, be it your own code appending the length on the prefix of the message or some other library that handles message framing for you like WCF. 更高级别的应用程序层负责这样做,无论是你自己的代码在消息的前缀上附加长度,还是像WCF那样为你处理消息框架的其他库。

Here is a full example showing a length prefixed implementation like you suggested in your question. 这是一个完整的示例,显示了您在问题中建议的长度前缀实现。

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

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