如果socket连接服务器失败,会继续尝试连接。但是界面会卡住,该如何解决

Simon612 Simon612 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

public delegate void connDelegate();
private void conn()
{
try
{
socket.Connect(ipe); //连接到服务器
listBox1.Items.Add("socket连接成功,准备接收数据...");
listBox1.Refresh();
showLB1.Text = "socket连接成功,准备接收数据...";
showLB1.Refresh();
}
catch (Exception ee)
{
Console.WriteLine("Exception:{0}", ee);
listBox1.Items.Add("连接失败,正在重试,请稍后!");
listBox1.Refresh();
showLB1.Text = "连接失败,正在重试,请稍后! ";
showLB1.Refresh();
}
}

private void okBtn_Click(object sender, EventArgs e)
{
connDelegate connDele = new connDelegate(conn);
this.ip = ipTB.Text;
portS = portTB.Text;
this.path = textBox1.Text;
if (this.ip == "" || portS == "" || this.path == "")
{
showLB1.Text = "ip,port和文件的输入框不能为空!";
}
MessageBox.Show(ip);

this.port = int.Parse(portS);
try
{
//创建终结点EndPoint
ipaddress = IPAddress.Parse(this.ip);
ipe = new IPEndPoint(ipaddress, this.port);

//创建Socket并连接到服务器
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
while (!socket.Connected)
{
Thread.Sleep(2000);
Invoke(connDele);
}

}
...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
Simon612
C# 111,130 成员 642,540 内容