windows System.Net.Sockets - 定义超时?(C#)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7881863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:20:52  来源:igfitidea点击:

System.Net.Sockets - define a timeout? (C#)

c#.netwindows

提问by Mike

Is it possible to set a timeout when performing a port lookup as demonstrated in the code below?:

执行端口查找时是否可以设置超时,如下面的代码所示?:

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

    }

采纳答案by Drew Gaynor

Looks like this may be what you're looking for: http://www.codeproject.com/KB/IP/TimeOutSocket.aspx.

看起来这可能就是您要查找的内容:http: //www.codeproject.com/KB/IP/TimeOutSocket.aspx

It seems that he's using

好像他在用

    ManualResetEvent.WaitOne()

to block the main thread for the duration of the time-out. If

在超时期间阻塞主线程。如果

    IsConnectionSuccessful

is false (i.e., the connection was not made in time or the callBack failed) when time runs out, an exception will be thrown.

为false(即连接未及时或callBack失败),超时则抛出异常。

回答by Marco

Use code taken from 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.");
}

回答by Siva Charan

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;