执行端口查找时是否可以设置超时值,如下面的代码所示?
try { System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); sock.Connect(ipa, portno1); if (sock.Connected == true) // Port is in use and connection is successful { displayGreen1(); } sock.Close(); }
看起来像这可能是你在找什么: http : //www.codeproject.com/KB/IP/TimeOutSocket.aspx 。
看来他在用
ManualResetEvent.WaitOne()
在超时期间阻塞主线程。 如果
IsConnectionSuccessful
是错误的(即,连接没有及时或回调失败)时间用完时,将抛出异常。
使用从这里取得的代码
Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect using a timeout (5 seconds) IAsyncResult result = socket.BeginConnect(sIP, iPort, null, null); bool success = result.AsyncWaitHandle.WaitOne(5000, true); if (!_socket.Connected) { // NOTE, MUST CLOSE THE SOCKET socket.Close(); throw new ApplicationException("Failed to connect server."); }
FYI …
Socket tcpSocket; // Set the receive buffer size to 8k tcpSocket.ReceiveBufferSize = 8192; // Set the timeout for synchronous receive methods to // 1 second (1000 milliseconds.) tcpSocket.ReceiveTimeout = 1000; // Set the send buffer size to 8k. tcpSocket.SendBufferSize = 8192; // Set the timeout for synchronous send methods // to 1 second (1000 milliseconds.) tcpSocket.SendTimeout = 1000;