如何检查线程中是否有tcp端口?我尝试使用后台工作线程,并且工作,但更新速度相当缓慢。我想向我的UI线程报告进度。这是一个正确的方法吗?检查端口是否开放以连接到线程?
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;
}
}
你见过这个问题吗? http://stackoverflow.com/questions/570098/in-c-how-to-check-if-a-tcp-port-is-available – fassetar
虽然我不想检查自己的ipaddress。 –
我正在检查远程服务器的端口,看它是否可以连接到。 –