探测端口!

wang_cheng_job 2010-01-16 04:18:11
我现在知道一个IP 61.203.487.84 和一个端口 123

要怎样使得这个探测的时间很短 不至于让用户等得不耐烦
下面是我的代码!
foreach (DataGridViewRow row in this.Dgvdete.Rows)
{
string ips= row.Cells[0].Value.ToString();
string port= row.Cells[1].Value.ToString();
IPAddress ip = IPAddress.Parse(ips);
DataGridViewImageCell imgcell = (DataGridViewImageCell)row.Cells[2];
imgcell.Value = imageList1.Images[1];
try
{
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(port));
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.SendTimeout = 1;
sock.Connect(point);
imgcell.Value = imageList1.Images[0];
//Execute(string dosCommand, int milliseconds)
}
catch
{
imgcell.Value = imageList1.Images[1];
}
}

我现在的问题是当一个端口没有开发的时候!在探测的时候要等一段时间大约是(30多秒)
我该怎样使得它的探测时间在1到2秒!


...全文
72 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Carpathia 2010-01-16
  • 打赏
  • 举报
回复

/// <summary>
/// 启动连接
/// </summary>
private bool Connection(string DeviceIP, int DevicePort)
{
try
{
tcpClientSocket = new TcpClient();
if (!Connect(DeviceIP, DevicePort, 1000))
{
return false;
}
tcpClientSocket.SendTimeout = 3000;
tcpClientSocket.ReceiveTimeout = 3000;
//tcpClientSocket.Connect(DeviceIP, DevicePort);
ns = tcpClientSocket.GetStream();
ns.WriteTimeout = 1000;
strReader = new StreamReader(ns);

return true;
}
catch (Exception ex)
{
return false;
}
}

private bool IsConnectionSuccessful = false;
private Exception socketexception;
private ManualResetEvent TimeoutObject = new ManualResetEvent(false);

public bool Connect(string serverip, int serverport, int timeoutMSec)
{
TimeoutObject.Reset();
socketexception = null;
tcpClientSocket = new TcpClient();

tcpClientSocket.BeginConnect(serverip, serverport,
new AsyncCallback(CallBackMethod), tcpClientSocket);

if (TimeoutObject.WaitOne(timeoutMSec, false))
{
if (IsConnectionSuccessful)
{
return true;
}
else
{
return false;
}
}
else
{
tcpClientSocket.Close();
return false;
}
}
private void CallBackMethod(IAsyncResult asyncresult)
{
try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult.AsyncState as TcpClient;

if (tcpclient.Client != null)
{
tcpclient.EndConnect(asyncresult);
IsConnectionSuccessful = true;
}
}
catch (Exception ex)
{
IsConnectionSuccessful = false;
socketexception = ex;
}
finally
{
TimeoutObject.Set();
}
}

以前写的,希望对你有帮助

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧