TCPClient 未读取传入数据

发布于 2024-11-10 04:05:35 字数 888 浏览 5 评论 0原文

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

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

我检查了 Wire-Shark 等网络嗅探工具,可以看到我的网络接口正在接收来自主机的数据。为什么我的 TCPClient 无法读取此数据?

WireShark 显示的接收数据的十六进制转储以 00 开头,这是否意味着空字符,给 TCPClient 读取带来问题?

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);

这是用于读取的代码...

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

谢谢你的帮助。

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.

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.

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?

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

Here's the code for writing ...

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();

Thanks for help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏九 2024-11-17 04:05:35

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

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

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? )

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文