thanks to this answer I was able to determine if Server is listening on a given port or not:
How to configure socket connect timeout
now I'm trying to create an endless loop, which will be loaded on form_load event and will be constantly checking if server is listening.
here is my code:
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";}
If I put following code into "on_button_click" event - everything works fine (except for - I have to click the button every single time I want to refresh status)
and when I create endless loop - I'm not getting any results at all:
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();
}
}
I guess it has something to do with threading but I just can't figure it out. What might be the problem?
Edit:
timer tick solution:
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();
}
}