2011-10-24 67 views
1

是否有可能设置超时如下?:的System.Net.Sockets - 定义超时? (C#)

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(); 

    } 
+3

这是重复http://stackoverflow.com/questions/456891/how-do-i-set-the-time-out-of-a-socket-connect-call – robowahoo

回答

0

看起来这可能是你在找什么:http://www.codeproject.com/KB/IP/TimeOutSocket.aspx

看来,他的使用

ManualResetEvent.WaitOne() 

来阻塞超时的持续时间的主线程。如果

IsConnectionSuccessful 

如果时间用完,将会抛出异常(即连接未及时完成或callBack失败)。

+0

@PeterManton只是* * **一个端口查找。如果你的内涵是'口scanning'忘记它。 –

3

使用代码的代码here

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."); 
} 
0

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;