diff --git a/websocket-sharp/WebSocket.cs b/websocket-sharp/WebSocket.cs index c4e803ed6..cdca5c8bc 100644 --- a/websocket-sharp/WebSocket.cs +++ b/websocket-sharp/WebSocket.cs @@ -112,6 +112,7 @@ public class WebSocket : IDisposable private Uri _uri; private const string _version = "13"; private TimeSpan _waitTime; + private TimeSpan _tcpTimeout; #endregion @@ -244,6 +245,7 @@ public WebSocket (string url, params string[] protocols) _message = messagec; _secure = _uri.Scheme == "wss"; _waitTime = TimeSpan.FromSeconds (5); + _tcpTimeout = TimeSpan.FromSeconds (30); init (); } @@ -610,6 +612,23 @@ public TimeSpan WaitTime { } } + /// + /// Gets or sets the timout for connecting using new + /// + /// + /// A that represents the timeout. The default value is the same as + /// 30 seconds. + /// + public TimeSpan TcpTimeout { + get { + return _tcpTimeout; + } + + set { + _tcpTimeout = value; + } + } + #endregion #region Public Events @@ -1723,7 +1742,7 @@ private void sendProxyConnectRequest () if (_proxyCredentials != null) { if (res.HasConnectionClose) { releaseClientResources (); - _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port); + _tcpClient = tcpClientWithTimeout (_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream (); } @@ -1745,12 +1764,12 @@ private void sendProxyConnectRequest () private void setClientStream () { if (_proxyUri != null) { - _tcpClient = new TcpClient (_proxyUri.DnsSafeHost, _proxyUri.Port); + _tcpClient = tcpClientWithTimeout (_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream (); sendProxyConnectRequest (); } else { - _tcpClient = new TcpClient (_uri.DnsSafeHost, _uri.Port); + _tcpClient = tcpClientWithTimeout (_uri.DnsSafeHost, _uri.Port); _stream = _tcpClient.GetStream (); } @@ -1782,6 +1801,19 @@ private void setClientStream () } } + // As client + private TcpClient tcpClientWithTimeout (string hostname, int port) + { + TcpClient client = new TcpClient (); + var result = client.BeginConnect (hostname, port, null, null); + var success = result.AsyncWaitHandle.WaitOne (_tcpTimeout); + if (!success) { + throw new WebSocketException ("The connection timed out"); + } + client.EndConnect (result); + return client; + } + private void startReceiving () { if (_messageEventQueue.Count > 0)