如何确保NetworkStream在不关闭Stream或TcpClient的情况下立即发送数据? [英] How to ensure NetworkStream to send data immediately without closing the Stream or TcpClient?

查看:45
本文介绍了如何确保NetworkStream在不关闭Stream或TcpClient的情况下立即发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的代码段,尝试通过 TcpClient 及其关联的 NetworkStream 发送数据.

I have a very simple code snippet that tries to send data via TcpClient and its associated NetworkStream.

var client = new TcpClient("xxx.xxx.xxx.xxx", 1234);
NetworkStream stream = client.GetStream();
byte[] buffer = Encoding.ASCII.GetBytes(str);
stream.Write(buffer, 0, buffer.Length);

我发现通常在 stream.Write()之后不会立即发送数据.如果添加 client.Close() stream.Close(),则将发送数据.但是,就我而言,我试图等待服务器发送回一些ACK消息,因此我想重用原始的 NetworkStream 而不关闭 TcpClient NetworkStream .该怎么办?

I've found that usually the data won't be sent immediately after stream.Write(). If I add client.Close() or stream.Close() then data will be sent. However, in my case, I'm trying to wait for the server to send some ACK message back so I want to reuse the original NetworkStream without closing either the TcpClient or NetworkStream. How can this be done?

推荐答案

设置从MSDN库文档中:

当NoDelay为 false 时,TcpClient在收集了大量传出数据之前不会通过网络发送数据包.由于TCP段中的开销很大,因此发送少量数据效率很低.但是,确实存在您需要发送少量数据或期望您发送的每个数据包都能立即做出响应的情况.您的决定应权衡网络效率与应用程序需求的相对重要性.

When NoDelay is false, a TcpClient does not send a packet over the network until it has collected a significant amount of outgoing data. Because of the amount of overhead in a TCP segment, sending small amounts of data is inefficient. However, situations do exist where you need to send very small amounts of data or expect immediate responses from each packet you send. Your decision should weigh the relative importance of network efficiency versus application requirements.

这篇关于如何确保NetworkStream在不关闭Stream或TcpClient的情况下立即发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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