执行端口查找时是否可以设置超时,如下面的代码所示?:
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();
}
答案 0 :(得分: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.");
}
答案 1 :(得分: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;
答案 2 :(得分:0)
看起来这可能是您正在寻找的内容:http://www.codeproject.com/KB/IP/TimeOutSocket.aspx。
似乎他正在使用
ManualResetEvent.WaitOne()
在超时期间阻止主线程。如果
IsConnectionSuccessful
为假(即连接未及时或callBack失败),当时间用完时,将抛出异常。