【发布时间】:2012-04-07 05:33:49
【问题描述】:
感谢这个答案,我能够确定服务器是否正在侦听给定端口:
How to configure socket connect timeout
现在我正在尝试创建一个无限循环,它将在 form_load 事件中加载,并且会不断检查服务器是否正在监听。
这是我的代码:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect("192.168.0.131", 1095, null, null);
bool success = result.AsyncWaitHandle.WaitOne(500, true);
if (!socket.Connected)
{label3.Text = "can't use"; socket.Close();}
else
{label3.Text = "start action";}
如果我将以下代码放入“on_button_click”事件 - 一切正常(除了 - 我每次想要刷新状态时都必须单击按钮)
当我创建无限循环时 - 我根本没有得到任何结果:
while (true)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect("192.168.0.131", 1095, null, null);
bool success = result.AsyncWaitHandle.WaitOne(500, true);
if (!socket.Connected)
{
label3.Text = "can't use";
socket.Close();
}
else
{
//success = true;
label3.Text = "start action";
socket.Close();
}
}
我想这与线程有关,但我就是想不通。可能是什么问题?
编辑:
定时器滴答解决方案:
private void Form1_Load_1(object sender, EventArgs e)
{
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (200);
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
public void MyTimer_Tick(object sender, EventArgs e)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect("192.168.0.131", 1095, null, null);
bool success = result.AsyncWaitHandle.WaitOne(500, true);
if (!socket.Connected)
{
label3.Text = "can't use";
socket.Close();
//throw new ApplicationException();
}
else
{
//success = true;
label3.Text = "start action";
socket.Close();
}
}
【问题讨论】:
-
你的
on_button_click方法中有这段代码吗? -
它在 button_click 事件中。现在它在 form_load 事件中;)
标签: c# multithreading loops infinite-loop