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();
}
}
You can add a Timer object to your form. Start the timer on the form load, and in the timerTickevent, run your code that you have in the infinite loop.Note: DO NOT include the
while(true)loop, just the code inside the loop. You really don’t want an infinite loop in your GUI thread 🙂EDIT
I still think you may need to consider a redesign of the app behavior, but this should be better than the Timer I suggested earlier
A somewhat better approach to the Timer (which should take care of the UI lag issue) would be for you to add a BackgroundWorker to your UI. Add a
DoWorkmethod similar to this:Note: If you were using .Net 4.0, you may want to consider using the task factory and a cancellation token rather than the BackgroundWorker, but either one should get you up and running.