TCPClient - 一段时间后停止接收数据
本文关键字:数据 一段时间 TCPClient | 更新日期: 2023-09-27 18:33:28
我编写了一段代码来侦听TCP模式下特定端口上的数据。现在这里的问题是下面的代码从远程接收一些数据,一段时间后它没有收到任何东西
我已经检查了wireshark,数据正在那里我已经检查了TCPView,端口(同一端口的2-3个条目)与应用程序一起打开,但很少有端口状态保持为"已建立",一个端口显示"正在侦听"
如果我正在检查 wireshark 是否有错误的数据详细信息,那么我发现远程 IP 端口对在 TCPView 中声明为"已建立",但它无法在日志文件中写入任何内容
我的问题是为什么我的应用程序中没有收到任何数据。代码中有什么问题吗?我已经尝试了谷歌可以提供的所有选项,但没有运气。
TcpListener tcpListenerDeviceResponse = new TcpListener(new IPEndPoint(IPAddress.Parse(localIP), 6005));
tcpListenerDeviceResponse.Start();
while (true)
{
using (TcpClient client = tcpListenerDeviceResponse.AcceptTcpClient())
{
// Get a stream object for reading and writing
using (NetworkStream stream = client.GetStream())
{
Socket skSource = client.Client;
int i;
var data2 = new byte[client.ReceiveBufferSize];
// Loop to receive all the data sent by the client.
while ((i = stream.Read(data2, 0, data2.Length)) != 0)
{
// Translate data bytes to a ASCII string.
string strResponse = System.Text.Encoding.ASCII.GetString(data2, 0, i);
// Insert the data in log text file
// process data
}
stream.Close();
}
// Shutdown and end connection
client.Close();
}
}
tcpListenerDeviceResponse.Stop();
一个原因可能是超时!
假设传输套接字发送的数据不超过接收套接字的超时,则会导致超时错误,并将中断while
循环并关闭套接字。
此 MSDN 链接可能会对您有所帮助!
另外,我建议您仅在由于超时以外的其他原因而中断while
时才关闭套接字。如果发生超时,请再次继续阅读。