是否可以在执行端口查找时设置超时,如以下代码所示:
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();
}发布于 2011-10-25 05:13:20
看起来这可能就是你要找的:http://www.codeproject.com/KB/IP/TimeOutSocket.aspx。
看起来他在利用
ManualResetEvent.WaitOne()在超时期间阻塞主线程。如果
IsConnectionSuccessful为false (即连接未及时建立或callBack失败),则会在超时时抛出异常。
发布于 2011-10-25 04:59:06
使用取自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.");
}发布于 2011-10-25 05:01:36
仅供参考。
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;https://stackoverflow.com/questions/7881863
复制相似问题