本文介绍了如何确保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?

推荐答案

设置 TcpClient.NoDelay 改为 true ,以便未使用Nagle的算法.

从MSDN库文档中:

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

09-26 20:51