我手上有问题。我有一个程序,其中客户端(form1)在无法连接到服务器时必须尝试重新连接。我必须进行重新连接的循环位于 Fomr_load 内部,因此重新连接是自动的。但问题是应用程序在 form_load 完成之前不会打开。谁知道我要去哪里请告诉我
private void Form1_Load(object sender, EventArgs e)
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
try
{
Socket Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(IP_End);
if (Client.Connected)
{
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
else
{
reconnect();
}
}
catch (SocketException)
{
reconnect();
}
}
private void reconnect()
{
try
{
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
Client.Connect(IP_End);
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
catch (SocketException)
{
reconnect();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (Client.Connected)
{
try
{
receive = STR.ReadLine();
label1.Invoke(new MethodInvoker(delegate () { label1.Text = (receive + "\n\r"); }));
receive = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}