我在Xamarin.Android中使用以下TCPListener,它在过去一直很好用,但只有一个问题...
在startListener()
(下面的完整代码)
while (!NS.DataAvailable && sta)
{
System.Threading.Thread.Sleep(50);
if (cntr > 20)
{
TCPC.Close();
NS = null;
break;
}
cntr++;
}
如果NetworkSteam没有数据发送(回复)或接收一段时间,TCPClient将关闭,这不是问题,需要它关闭它。
问题是我可以设置这个"超时"在更改Thread.Sleep(50)
值和cntr > 20
值之间,但很难根据收到的数据预测此超时需要多长时间,因为我需要在发送数据之前对数据执行长时间运行操作回复(长时间运行可能是3秒或30秒),如果我设置得太短,那么它在我能够回复之前关闭我的TCP客户端,如果我设置太长时间端口被阻止了几秒钟后发送回复和在此超时到期之前,我无法发送下一个命令。有没有更好的方法来处理此超时,或更好的实现不使用TCPListener
private static void startListener()
{
ListenStarted = true;
TCPL = new TcpListener(IPAddress.Any, 8012);
try
{
TCPL.Start();
sta = true;
}
catch (Exception e)
{
//Log Error
}
while (sta)
{
try
{
TCPC = TCPL.AcceptTcpClient();
TCPC.NoDelay = true;
NS = TCPC.GetStream();
while (NS.CanRead && NS.CanWrite && sta)
{
StringBuilder sb = new StringBuilder();
int cntr = 0;
while (!NS.DataAvailable && sta)
{
System.Threading.Thread.Sleep(50);
if (cntr > 20)
{
TCPC.Close();
NS = null;
break;
}
cntr++;
}
if (NS == null)
break;
while (NS.DataAvailable && sta)
{
int bte = NS.ReadByte();
if (bte == -1)
break;
if ((char)bte != (char)0x03)
{
sb.Append((char)bte);
}
else
{
processDataSets(sb);
break;
}
}
}
}
catch (Exception e)
{
sta = false;
}
}
ListenStarted = false;
NS = null;
}