TCPClient 未读取传入数据 [英] TCPClient not reading the incoming data

查看:51
本文介绍了TCPClient 未读取传入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 C# 应用程序,它通过 TCP/IP 连接到主机,然后使用 TCPClient Stream 发送和接收响应.

I am working on a C# Application which connects to the host over TCP/IP to send and then receive the response using TCPClient Stream.

问题是我可以使用 Stream.Write(...) 发送数据,但是当我尝试通过调用 Stream.Read(...) 来获取对我发送的数据的响应时,它挂起并且永远不会返回.

The Problem is I can send data using the Stream.Write(...) but when I try to get the response against my sent data by calling Stream.Read(...), it hangs and never returns.

我检查了像 Wire-Shark 这样的网络嗅探工具,可以看到我的网络接口正在接收来自主机的数据.为什么我的 TCPClient 没有读取这些数据?

I've checked the Network sniffing tool like Wire-Shark and can see that the data from the host is being received by my network interface. Why this data is not getting read by my TCPClient?

WireShark 显示的接收数据的 Hex dump 以 00 开头,是否表示 Null 字符,导致 TCPClient 无法读取?

The Hex dump of the received data shown by WireShark starts with 00, does it mean a Null character, creating problem for the TCPClient to read?

00-1d-4f-fb-43-4b-00-1d-7e-3a-9a-20-08-00-45-00-00-34

00-1d-4f-fb-43-4b-00-1d-7e-3a-9a-20-08-00-45-00-00-34

这是编写...的代码

myTcpClient = new TcpClient();
myTcpClient.Connect("192.168.0.194", 1958);
Stream myTCPStream = myTcpClient.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] msgBytes = asen.GetBytes("Message to be sent.");
myTCPStream.Write(msgBytes, 0, msgBytes.Length);

这是阅读的代码......

and that is the code for reading ...

byte[] bytesReceived = new byte[100];
int nBytesRead = myTCPStream.Read(bytesReceived, 0, bytesReceived.Length);
myTcpClient.Close();

感谢您的帮助.

推荐答案

这可能是时间问题,但是没有看到你的代码很难说(你是在发送数据包后直接运行读取代码吗?是吗?在同一个线程上?)

This could be a timing issue, but it is hard to say without seeing your code (are you running the read code directly after you send the packet? is it on the same thread? )

另一个想法:尝试设置 NoDelay 属性为真.这告诉 TCP 堆栈立即将数据传递给您的应用程序,而不是等待一个完整的缓冲区(禁用 Nagle算法).这对于减少发送 & 时的延迟很有用.接收小数据包.

Another thought: Try setting the NoDelay property to true. This tells the TCP stack to pass data to your app immediately rather than waiting for a full buffer (disabling the Nagle algorithm). This is useful for reducing latency when sending & receiving small packets of data.

这篇关于TCPClient 未读取传入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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