如果超时设置超过1000毫秒,我似乎无法让网络流获得读取超时异常。这有意义吗?
private void startListening()
{
while (!_shouldStop)
{
_terminate = false;
try
{
sendMessageToParent(String.Format("Waiting for a connection on {0}:{1}",_IP,_PORT));
Program.sendNotifyIconMessage("MediaSync - Started");
TcpClient c = l.AcceptTcpClient();
sendMessageToParent("Client connected...");
ns = c.GetStream();
ns.ReadTimeout = 5000;
// ns.WriteTimeout = 10000;
while (!_shouldStop && !_terminate)
{
try
{
getHeader2();
// getHeader();
}
catch (Exception e)
{
sendMessageToParent(e.Message);
sendMessageToParent("Exception: " + e.Message,true);
_terminate = true;
break;
}
}
}
catch (Exception e)
{
sendMessageToParent("Stopped");
sendMessageToParent("Exception: " + e.Message,true);
return;
}
}
}
private void getHeader2()
{
bool headerComplete = false;
int headerBytesRead = 0;
//header = new MyHeader();
Stopwatch stopWatch = new Stopwatch();
while (!headerComplete)
{
stopWatch.Start();
if (headerOffset > 0)
{
headerString += System.Text.Encoding.ASCII.GetString(buffer, headerOffset, b - headerOffset);
// this was how much was read from the offset
headerBytesRead += b - headerOffset;
headerOffset = 0;
}
header = new MyHeader(headerString.Split(',').Select(t => t.Split('=')).ToArray());
if (!header.isHeaderComplete())
{
b = ns.Read(buffer, 0, buffer.Length);
headerBytesRead += b;
if (b < 1)
{
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
if (ts.Seconds >= 5)
{
sendMessageToParent("Past limit");
ns.Close();
}
else
{
stopWatch.Start();
}
}
else
{
stopWatch.Reset();
}
headerString += System.Text.Encoding.ASCII.GetString(buffer, 0, b);
}
else
{
contentOffset = b - (headerBytesRead - header.HeaderLength);
headerComplete = true;
}
}
sendMessageToParent(String.Format("Received header data: {0}", header.HeaderData));
processAction();
}
看起来5000毫秒是一个神奇的数字,它可以达到4000.是否存在某些我不知道的固有限制?
好的,我更新了代码以显示我在做什么。我发现了一种解决方法,使用秒表并检查在预期时间内是否没有读取数据。它可以工作,但我仍然想知道是否真的有超时限制器。其中一个答案表明了这一点。任何人都可以确认吗?