我需要下载一个文件并用它来连接服务器。如果连接失败,则重新启动循环。不知怎的,while循环不断运行和下载文件。我认为布尔 Globals.sockRetry 会发生一些奇怪的事情,但我无法找到真正发生的事情。
public class Globals
{
public static string serverIp;
public static int serverPort;
public static int sockConn = 0;
public static bool sockRetry = false;
public static TcpClient client;
public static NetworkStream nwStream;
public static StreamReader reader;
public static StreamWriter writer;
}
static void connect(Globals g)
{
Globals.sockConn = 1;
try
{
Globals.client = new TcpClient(Globals.serverIp, Globals.serverPort);
Globals.nwStream = Globals.client.GetStream();
Globals.reader = new StreamReader(Globals.nwStream);
Globals.writer = new StreamWriter(Globals.nwStream);
Globals.sockConn = 2;
string inputLine;
while ((inputLine = Globals.reader.ReadLine()) != null)
{
// ParseMessage(Globals.writer, inputLine, g);
}
}
catch
{
Globals.sockRetry = true;
Globals.sockConn = 0;
return;
}
}
static void getInfo()
{
while (true)
{
try
{
WebRequest request = WebRequest.Create(INFO_HOST + INFO_PATH);
WebResponse response = request.GetResponse();
string content;
using (var sr = new StreamReader(response.GetResponseStream()))
{
content = sr.ReadToEnd();
}
string[] contentArray = content.Split(':');
string serverIp = contentArray[0];
string serverPortStr = contentArray[1];
int serverPort = 5000;
Int32.TryParse(serverPortStr, out serverPort);
Globals g = new Globals();
Globals.serverIp = serverIp;
Globals.serverPort = serverPort;
while (Globals.sockConn == 0)
{
if (Globals.sockRetry == false)
{
connect(g);
}
else
{
// error connecting
// wait and retry
Globals.sockRetry = false;
Thread.Sleep(60000);
break;
}
}
continue;
}
catch
{
// error downloading file
// wait and retry
Thread.Sleep(60000);
continue;
}
}
}
答案 0 :(得分:5)
你终止循环的唯一地方是:
if (Globals.sockRetry == false)
{
connect(g);
}
else
{
...
break;
}
所以只有在Globals.sockRetry == true
时才会发生。仅在抛出异常时才为Globals.sockRetry
分配true
。如果没有抛出异常,则循环永远不会结束。
像这样改变:
if (Globals.sockRetry == false)
{
connect(g);
break;
}
否则,在连接后,您将再次连接,然后再次连接,直到抛出异常(希望如此)。
答案 1 :(得分:1)
continue
继续循环中的下一次迭代。
break
停止循环。所以,循环永远不会结束。
如果要停止循环,请将sockRetry
设置为false
,以便执行此操作:while (sockRetry)