【发布时间】:2013-08-25 14:59:29
【问题描述】:
如果 bool 为真,我有办法告诉 TCP 客户端一遍又一遍地连接,但我不知道这是否真的是一个好方法,因为我几乎告诉过它和以上,并忽略错误。
但我也不知道有其他方法可以做到这一点。
但也许你们会这样做,这是代码的一部分:
while (capcon == true)
{
using (tcp = new TcpClient())
{
tcp.NoDelay = true;
try
{
if (!tcp.Connected)
tcp.Connect(adress);
}
catch (Exception e)
{
if (e is SocketException || e is IOException) { }
else
MessageBox.Show(e.Message + " Tcp Connect : Send");
}
using (var ms = new MemoryStream())
{
Stoptimer = new Stopwatch();
int i = 0;
while (tcp.Connected && capcon == true)
{
try
{
FastMethods.CaptureBitBit(hwnd, JpegParam, jpeg, ms);
if (bsize != ms.Length && tcp.Connected)
{
bsize = ms.Length;
Stoptimer.Start();
tcp.GetStream().Write(BitConverter.GetBytes(bsize), 0, intsize);
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize);
//i++;
//tcp.GetStream().Write(rv, 0, rv.Length);
if (i > 100)
{
i = 0;
Stoptimer.Stop();
Console.WriteLine(Stoptimer.ElapsedTicks);
Stoptimer = new Stopwatch();
}
}
ms.SetLength(0);
}
catch (Exception e)
{
if (e is SocketException || e is IOException)
{
break;
}
else
{
MessageBox.Show(e.Message + ": Send Error");
}
}
}
}
}
}
嗯,如你所见,这是一团糟,但这是我得到的。
【问题讨论】:
-
您错过了实际停止尝试连接的部分(连接成功时)...
-
当它成功时,它会将代码继续到另一个while循环,然后它就完成了。如果连接失败,它会中断;使其运行到前一个 While 循环,该循环告诉它重新连接。
-
忽略异常绝不是一个好主意。有些表示可以通过重试恢复的条件:有些则不能。
-
如果可以的话,我如何告诉它重试?我只知道 SocketExeption 和 IOException,如果连接失败似乎都会发生