17 private const int created = 0;
19 private const int connecting = 1;
21 private const int connected = 2;
23 private const int disposed = 3;
35 if (innerWebSocket !=
null)
49 if (innerWebSocket !=
null)
63 if (innerWebSocket !=
null)
77 if (innerWebSocket !=
null)
79 return innerWebSocket.
State;
105 Logging.Enter(Logging.WebSockets,
this,
".ctor",
null);
107 if (!WebSocketProtocolComponent.IsSupported)
109 WebSocketHelpers.ThrowPlatformNotSupportedException_WSPC();
116 Logging.Exit(Logging.WebSockets,
this,
".ctor",
null);
145 options.SetToReadOnly();
146 return ConnectAsyncCore(uri, cancellationToken);
159 Logging.Associate(Logging.WebSockets,
this, request);
161 connectCancellation = cancellationToken.
Register(AbortRequest, request, useSynchronizationContext:
false);
165 Logging.Associate(Logging.WebSockets,
this, response);
167 string subProtocol = ValidateResponse(request, response);
168 innerWebSocket = WebSocket.
CreateClientWebSocket(response.
GetResponseStream(), subProtocol, options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, useZeroMaskingKey:
false, options.GetOrCreateBuffer());
171 Logging.Associate(Logging.WebSockets,
this, innerWebSocket);
175 throw new ObjectDisposedException(GetType().FullName);
178 catch (WebException innerException)
180 ConnectExceptionCleanup(response);
181 WebSocketException ex =
new WebSocketException(SR.GetString(
"net_webstatus_ConnectFailure"), innerException);
184 Logging.Exception(Logging.WebSockets,
this,
"ConnectAsync", ex);
190 ConnectExceptionCleanup(response);
193 Logging.Exception(Logging.WebSockets,
this,
"ConnectAsync", e);
203 private void ConnectExceptionCleanup(HttpWebResponse response)
209 private HttpWebRequest CreateAndConfigureRequest(Uri uri)
211 HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
212 if (httpWebRequest ==
null)
214 throw new InvalidOperationException(SR.GetString(
"net_WebSockets_InvalidRegistration"));
216 foreach (
string key
in options.RequestHeaders.Keys)
218 httpWebRequest.Headers.Add(key, options.RequestHeaders[key]);
220 if (options.RequestedSubProtocols.Count > 0)
222 httpWebRequest.Headers.Add(
"Sec-WebSocket-Protocol",
string.Join(
", ", options.RequestedSubProtocols));
224 if (options.UseDefaultCredentials)
226 httpWebRequest.UseDefaultCredentials =
true;
228 else if (options.Credentials !=
null)
230 httpWebRequest.Credentials = options.Credentials;
232 if (options.InternalClientCertificates !=
null)
234 httpWebRequest.ClientCertificates = options.InternalClientCertificates;
236 httpWebRequest.Proxy = options.Proxy;
237 httpWebRequest.CookieContainer = options.Cookies;
238 cts.Token.Register(AbortRequest, httpWebRequest, useSynchronizationContext:
false);
239 return httpWebRequest;
242 private string ValidateResponse(HttpWebRequest request, HttpWebResponse response)
246 throw new WebSocketException(SR.GetString(
"net_WebSockets_Connect101Expected", (
int)response.StatusCode));
248 string text = response.Headers[
"Upgrade"];
251 throw new WebSocketException(SR.GetString(
"net_WebSockets_InvalidResponseHeader",
"Upgrade", text));
253 string text2 = response.Headers[
"Connection"];
256 throw new WebSocketException(SR.GetString(
"net_WebSockets_InvalidResponseHeader",
"Connection", text2));
258 string text3 = response.Headers[
"Sec-WebSocket-Accept"];
259 string secWebSocketAcceptString = WebSocketHelpers.GetSecWebSocketAcceptString(request.Headers[
"Sec-WebSocket-Key"]);
260 if (!
string.Equals(text3, secWebSocketAcceptString,
StringComparison.OrdinalIgnoreCase))
262 throw new WebSocketException(SR.GetString(
"net_WebSockets_InvalidResponseHeader",
"Sec-WebSocket-Accept", text3));
264 string text4 = response.Headers[
"Sec-WebSocket-Protocol"];
265 if (!
string.IsNullOrWhiteSpace(text4) && options.RequestedSubProtocols.Count > 0)
268 foreach (
string requestedSubProtocol
in options.RequestedSubProtocols)
270 if (
string.Equals(requestedSubProtocol, text4,
StringComparison.OrdinalIgnoreCase))
278 throw new WebSocketException(SR.GetString(
"net_WebSockets_AcceptUnsupportedProtocol",
string.Join(
", ", options.RequestedSubProtocols), text4));
281 if (!
string.IsNullOrWhiteSpace(text4))
296 ThrowIfNotConnected();
297 return innerWebSocket.
SendAsync(buffer, messageType, endOfMessage, cancellationToken);
306 ThrowIfNotConnected();
307 return innerWebSocket.
ReceiveAsync(buffer, cancellationToken);
317 ThrowIfNotConnected();
318 return innerWebSocket.
CloseAsync(closeStatus, statusDescription, cancellationToken);
328 ThrowIfNotConnected();
329 return innerWebSocket.
CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
337 if (innerWebSocket !=
null)
339 innerWebSocket.
Abort();
345 private void AbortRequest(
object obj)
348 httpWebRequest.
Abort();
357 cts.Cancel(throwOnFirstException:
false);
359 if (innerWebSocket !=
null)
366 private void ThrowIfNotConnected()
WebSocketCloseStatus
Represents well known WebSocket close codes as defined in section 11.7 of the WebSocket protocol spec...
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
Close the output for the T:System.Net.WebSockets.ClientWebSocket instance as an asynchronous operatio...
Propagates notification that operations should be canceled.
Options to use with a T:System.Net.WebSockets.ClientWebSocket object.
ClientWebSocketOptions Options
Gets the WebSocket options for the T:System.Net.WebSockets.ClientWebSocket instance.
abstract Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
Initiates or completes the close handshake defined in the WebSocket protocol specification section 7.
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
abstract string CloseStatusDescription
Allows the remote endpoint to describe the reason why the connection was closed.
WebSocketState
Defines the different states a WebSockets instance can be in.
WebSocketMessageType
Indicates the message type.
abstract WebSocketState State
Returns the current state of the WebSocket connection.
abstract void Abort()
Aborts the WebSocket connection and cancels any pending IO operations.
string Scheme
Gets the scheme name for this URI.
Represents a callback delegate that has been registered with a T:System.Threading....
HttpStatusCode
Contains the values of status codes defined for HTTP.
static int Exchange(ref int location1, int value)
Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operat...
override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
Close the T:System.Net.WebSockets.ClientWebSocket instance as an asynchronous operation.
override WebSocketState State
Get the WebSocket state of the T:System.Net.WebSockets.ClientWebSocket instance.
override string CloseStatusDescription
Gets a description of the reason why the T:System.Net.WebSockets.ClientWebSocket instance was closed.
override string SubProtocol
Gets the supported WebSocket sub-protocol for the T:System.Net.WebSockets.ClientWebSocket instance.
The exception that is thrown when an operation is performed on a disposed object.
bool IsAbsoluteUri
Gets whether the T:System.Uri instance is absolute.
The WebSocket class allows applications to send and receive data after the WebSocket upgrade has comp...
virtual Task< WebResponse > GetResponseAsync()
When overridden in a descendant class, returns a response to an Internet request as an asynchronous o...
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
Connect to a WebSocket server as an asynchronous operation.
override Task< WebSocketReceiveResult > ReceiveAsync(ArraySegment< byte > buffer, CancellationToken cancellationToken)
Receive data on T:System.Net.WebSockets.ClientWebSocket as an asynchronous operation.
override void Abort()
Aborts the connection and cancels any pending IO operations.
abstract Task SendAsync(ArraySegment< byte > buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
Sends data over the T:System.Net.WebSockets.WebSocket connection asynchronously.
Provides an HTTP-specific implementation of the T:System.Net.WebResponse class.
abstract Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
Closes the WebSocket connection as an asynchronous operation using the close handshake defined in the...
abstract Task< WebSocketReceiveResult > ReceiveAsync(ArraySegment< byte > buffer, CancellationToken cancellationToken)
Receives data from the T:System.Net.WebSockets.WebSocket connection asynchronously.
override? WebSocketCloseStatus CloseStatus
Gets the reason why the close handshake was initiated on T:System.Net.WebSockets.ClientWebSocket inst...
static WebSocket CreateClientWebSocket(Stream innerStream, string subProtocol, int receiveBufferSize, int sendBufferSize, TimeSpan keepAliveInterval, bool useZeroMaskingKey, ArraySegment< byte > internalBuffer)
This API supports the .NET Framework infrastructure and is not intended to be used directly from your...
Provides a client for connecting to WebSocket services.
The exception that is thrown when one of the arguments provided to a method is not valid.
abstract ? WebSocketCloseStatus CloseStatus
Indicates the reason why the remote endpoint initiated the close handshake.
override Task SendAsync(ArraySegment< byte > buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
Send data on T:System.Net.WebSockets.ClientWebSocket as an asynchronous operation.
Signals to a T:System.Threading.CancellationToken that it should be canceled.
abstract string SubProtocol
The subprotocol that was negotiated during the opening handshake.
The exception that is thrown when a method call is invalid for the object's current state.
ClientWebSocket()
Creates an instance of the T:System.Net.WebSockets.ClientWebSocket class.
abstract void Dispose()
Used to clean up unmanaged resources for ASP.NET and self-hosted implementations.
Provides an object representation of a uniform resource identifier (URI) and easy access to the parts...
static void RegisterPrefixes()
This API supports the .NET Framework infrastructure and is not intended to be used directly from your...
Provides an HTTP-specific implementation of the T:System.Net.WebRequest class.
override void Abort()
Cancels a request to an Internet resource.
override void Dispose()
Releases the unmanaged resources used by the T:System.Net.WebSockets.ClientWebSocket instance.
Provides atomic operations for variables that are shared by multiple threads.
CancellationTokenRegistration Register(Action callback)
Registers a delegate that will be called when this T:System.Threading.CancellationToken is canceled.
override Stream GetResponseStream()
Gets the stream that is used to read the body of the response from the server.
void Dispose()
Releases all resources used by the current instance of the T:System.Threading.CancellationTokenRegist...
Represents an asynchronous operation that can return a value.