Note that there are some explanatory texts on larger screens.

plurals
  1. POconstantly check if Server is listening on a given port with C#
    text
    copied!<p>thanks to this answer I was able to determine if Server is listening on a given port or not:</p> <p><a href="https://stackoverflow.com/questions/1062035/how-to-config-socket-connect-timeout-in-c-sharp">How to configure socket connect timeout</a></p> <p>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.</p> <p>here is my code:</p> <pre><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";} </code></pre> <p>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)</p> <p>and when I create endless loop - I'm not getting any results at all:</p> <pre><code>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(); } } </code></pre> <p>I guess it has something to do with threading but I just can't figure it out. What might be the problem?</p> <p><strong>Edit:</strong></p> <p>timer tick solution:</p> <pre><code>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(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload