Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions websocket-sharp/WebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ public class WebSocket : IDisposable
private Uri _uri;
private const string _version = "13";
private TimeSpan _waitTime;
private TimeSpan _tcpTimeout;

#endregion

Expand Down Expand Up @@ -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 ();
}
Expand Down Expand Up @@ -610,6 +612,23 @@ public TimeSpan WaitTime {
}
}

/// <summary>
/// Gets or sets the timout for connecting using new <see cref="TcpClient"/>
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the timeout. The default value is the same as
/// 30 seconds.
/// </value>
public TimeSpan TcpTimeout {
get {
return _tcpTimeout;
}

set {
_tcpTimeout = value;
}
}

#endregion

#region Public Events
Expand Down Expand Up @@ -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 ();
}

Expand All @@ -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 ();
}

Expand Down Expand Up @@ -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)
Expand Down