TcpClient连接延迟
本文关键字:延迟 连接 TcpClient | 更新日期: 2023-09-27 18:06:15
我迷路了。当我想编辑的东西在我的Form1然后我必须编辑后做命令Form1.show();所以我不编辑开放的形式,但一些看不见的新形式。我认为它是在构造器的某个地方,但我不知道在哪里。请帮助
Cli类:
public class Cli
{
Form1 frm;
TcpClient tcpclnt = new TcpClient();
public Cli()
{
}
public void Connect()
{
frm = new Form1();
try
{
frm.debug.Text = "Connecting";
tcpclnt.Connect("127.0.0.1", 8001);
// use the ipaddress as in the server program
frm.debug.Text = "Connected";
}
catch (Exception e)
{
frm.debug.Text=("Error..... " + e.StackTrace);
frm.Show();
}...
Form1类:
public partial class Form1 : Form
{
Cli client;
public int pocet = 0;
public Form1()
{
InitializeComponent();
client =new Cli();
Random rnd = new Random();
pocet = rnd.Next(23, 10000);
if (pocet % 2 == 1)
{
label1.Text = "HRAJEŠ";
}
else { label2.Text = "HRAJEŠ"; }
}...
没有无限循环,我认为您遇到了延迟,因为它正在等待TcpClient.Connect()
返回。
尝试异步连接。
frm.debug.Text = "Connecting";
var client = new TcpClient();
var result = client.BeginConnect("127.0.0.1", 8001, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
if (!success)
{
throw new Exception("Failed to connect.");
}
// we have connected
frm.debug.Text = "Connected";
client.EndConnect(result);