-1

How would I check if a tcp port is available in a thread? I tried using a background worker thread, and it worked, but updated rather slowly. I want to report progress to my UI thread. Is this a correct way?

    BackgroundWorker authStatus = new BackgroundWorker {WorkerReportsProgress = true};
    authStatus.DoWork += AuthStatusWork;
    authStatus.ProgressChanged += AuthStatusProgressChanged;

    public void AuthStatusWork(object sender, EventArgs e)
    {
        var thread = sender as BackgroundWorker;

        using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            socket.SendTimeout = 3;
            while (true)
            {
                try
                {
                    socket.Connect(auth[0], Convert.ToInt32(auth[1]));
                    if (thread != null) thread.ReportProgress(1);
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode != SocketError.ConnectionRefused &&
                        ex.SocketErrorCode != SocketError.TimedOut) continue;
                    if (thread != null) thread.ReportProgress(0);
                }
            }
        }
    }

    public void AuthStatusProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        switch (e.ProgressPercentage)
        {
            case 0:
                AuthStatus.Foreground = Brushes.Red;
                AuthStatus.Content = "Offline";
                break;
            case 1:
                AuthStatus.Foreground = Brushes.Green;
                AuthStatus.Content = "Online";
                break;
        }
    }

2 Answers2

2

Use asynchronous connections, as demonstrated here here

This will allow you to attempt to connect to as many remote tcp ports as you want and let you know when it succeeds or fails. You don't have to worry about how many threads you've started or running out of resources (other than sockets, which is a problem no matter what approach you take).

xaxxon
  • 18,514
  • 4
  • 45
  • 79
  • I have read the article, but cannot figure out when the connection is actually made, and when to signal to my UI thread that it has been. – Tristan McPherson Aug 16 '13 at 04:21
0

I'm trying to check a remote server's port to see whether or not it is available to connect to.

So try to connect to it. These games of trying to predict the future in some way are pointless. Try the connection and handle the error. This applies to any resource: the best way to see if any resource is available is to try to use it.

user207421
  • 298,294
  • 41
  • 291
  • 462