Message​Web​Socket Message​Web​Socket Message​Web​Socket Class


Supports network communication that allows reading and writing whole messages using a WebSocket.

public sealed class MessageWebSocket : IClosable, IMessageWebSocket, IMessageWebSocket2, IWebSocketpublic sealed class MessageWebSocket : IDisposable, IMessageWebSocket, IMessageWebSocket2, IWebSocketPublic NotInheritable Class MessageWebSocket Implements IDisposable, IMessageWebSocket, IMessageWebSocket2, IWebSocket
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
privateNetworkClientServer internetClient


The MessageWebSocket class provides a message-based abstraction of the WebSocket protocol. When using MessageWebSocket, the entire WebSocket message is read or written in a single operation. In contrast, the StreamWebSocket allows sections of a message to be read with each read operation, rather than requiring the entire message to be read in a single operation.

For UTF-8 messages, MessageWebSocket must be used. StreamWebSocket only supports binary messages.

Handling exceptions

You must write code to handle exceptions when you call asynchronous methods on the MessageWebSocket class. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and HTTP server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime.

The Windows.Networking.Sockets namespace has a convenient helper method and enumeration for handling errors when using WebSockets. This can be useful for handling specific network exceptions differently in your app. An app can also use the HRESULT from the exception on parameter validation errors to learn more detailed information on the error that caused the exception.

For more information on possible exceptions and how to handle exceptions, see Handling exceptions in network apps.

Using MessageWebSocket on Windows Server 2012

On Windows Server 2012 and Windows Server 2012 R2, the Windows.Networking.dll that implements most of the classes in the Windows.Networking.Sockets namespace will fail to load unless the Media Foundation feature is enabled. As a result, apps that use MessageWebSocket and related WebSocket classes in the Windows.Networking.Sockets namespace will fail if the Media Foundation feature is disabled. Windows Server 2012 or Windows Server 2012 R2 installs with the Media Foundation feature disabled.

The Media Foundation feature can be enabled on Windows Server 2012 or Windows Server 2012 R2 using Server Manager or by entering the following text in a command prompt or a script:

dism /online /enable-feature /featurename:ServerMediaFoundationAfter the Media Foundation feature is enabled, the user is prompted to restart. Once the computer is restarted, classes for sockets and WebSockets in the Windows.Networking.Sockets namespace will work as expected.


MessageWebSocket() MessageWebSocket() MessageWebSocket()

Creates a new MessageWebSocket object.

public MessageWebSocket()public MessageWebSocket()Public Sub New()


Control Control Control

Gets socket control data on a MessageWebSocket object.

public MessageWebSocketControl Control { get; }public MessageWebSocketControl Control { get; }Public ReadOnly Property Control As MessageWebSocketControl


The Control property gets the MessageWebSocketControl instance associated with a MessageWebSocket object.

A MessageWebSocketControl object is automatically created with the parent MessageWebSocket object. The MessageWebSocketControl instance can then be used to get or set control data used by the MessageWebSocket object. These properties on the MessageWebSocketControl instance include the following:

The SupportedProtocols property gets the value of this property and can be called at any time.

The MessageType property can be changed at any time before or after the MessageWebSocket is connected. This allows an app to switch between binary and UTF-8 messages when needed.

The OutboundBufferSizeInBytes property must be set before the MessageWebSocket is connected. Setting this property after the MessageWebSocket is connected has no effect.

Changes to any other property values on the MessageWebSocketControl must be set before the MessageWebSocket is connected. As a result if you need to make changes to the MaxMessageSize, OutboundBufferSizeInBytes, ProxyCredential, or ServerCredential properties, then these changes must occur before a successful call to the ConnectAsync method on the MessageWebSocket.

See Also

Information Information Information

Gets socket information on a MessageWebSocket object.

public MessageWebSocketInformation Information { get; }public MessageWebSocketInformation Information { get; }Public ReadOnly Property Information As MessageWebSocketInformation

OutputStream OutputStream OutputStream

Gets the output stream to write to the remote network destination on a MessageWebSocket object.

public IOutputStream OutputStream { get; }public IOutputStream OutputStream { get; }Public ReadOnly Property OutputStream As IOutputStream
IOutputStream IOutputStream IOutputStream

A sequential stream of bytes to be written to the remote destination as a single message.



This property is used with the DataWriter object to write outgoing data to be sent to the remote network destination on a socket object.

The following specific errors can occur when you call IOutputStream.FlushAsync on the OutputStream of a MessageWebSocket if the websocket is in an invalid state at the time.

  • If the websocket instance has been explicitly closed (via delete, Dispose, or Close) or implicitly closed (fallen out of scope), FlushAsync throws an RO_E_CLOSED exception.
  • If the IOutputStream object associated with the websocket has been explicitly closed (via delete, Dispose, or Close) or implicitly closed (for example, by disposing of a DataWriter instance before calling DetachStream on it), FlushAsync throws an RO_E_CLOSED exception.
  • If the websocket is not connected yet (ConnectAsync has not been called), then FlushAsync throws an E_ILLEGAL_METHOD_CALL exception.


Close() Close() Close()

Closes the MessageWebSocket object and sends an empty close frame to the server.

public void Close()This member is not implemented in C#This member is not implemented in VB.Net


The Close method is used by Windows app using JavaScript. For apps written using the .NET Framework 4.5 in C# and VB.NET, the Close method is exposed as the method on the MessageWebSocket. For apps written in C++, the Close method will be called when using the delete keyword on the object.

Close(UInt16, String) Close(UInt16, String) Close(UInt16, String)

Closes the MessageWebSocket object and indicates a reason for the closure.

public void Close(UInt16 code, String reason)This member is not implemented in C#This member is not implemented in VB.Net
System.UInt16 System.UInt16 System.UInt16

Status code indicating the reason for closure.

System.String System.String System.String

Optional UTF-8-encoded data with additional information about the closure.


ConnectAsync(Uri) ConnectAsync(Uri) ConnectAsync(Uri)

Starts an asynchronous operation to connect to a remote network destination on a MessageWebSocket object.

public IAsyncAction ConnectAsync(Uri uri)public IAsyncAction ConnectAsync(Uri uri)Public Function ConnectAsync(uri As Uri) As IAsyncAction
Uri Uri Uri

An absolute Uri for the server to connect to.


An asynchronous connect operation on a MessageWebSocket object.



The ConnectAsync method initiates the WebSocket handshake with a remote network destination, and then negotiates the subprotocol.

For WebSocket connections over TCP, use the ws:// scheme in the uri. For secure WebSocket connections over TLS/SSL, use the wss:// scheme.

See Also

Dispose() Dispose() Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

This member is not implemented in C++void Dispose()Sub Dispose

SetRequestHeader(String, String) SetRequestHeader(String, String) SetRequestHeader(String, String)

Adds an HTTP request header to the HTTP request message used in the WebSocket protocol handshake by the MessageWebSocket object.

public void SetRequestHeader(String headerName, String headerValue)public void SetRequestHeader(String headerName, String headerValue)Public Function SetRequestHeader(headerName As String, headerValue As String) As void
System.String System.String System.String

The name of the request header.

System.String System.String System.String

The value of the request header.



The SetRequestHeader method must be called prior to calling the ConnectAsync method. Calling the SetRequestHeader method after calling the ConnectAsync method will result in an error.

Using the SetRequestHeader method to add a Sec-WebSocket-Extensions header is not supported.


Closed Closed Closed

Occurs when a close frame is received on the MessageWebSocket object as part of the close handshake.

public event TypedEventHandler Closedpublic event TypedEventHandler ClosedPublic Event Closed


This event is only triggered if a close frame is received from the server or if Close is explicitly called on the local socket. If the underlying TCP connection is suddenly terminated, GetDataReader and/or GetDataStream throw the WININET_E_CONNECTION_ABORTED exception, without the Close event ever being raised.

Your code should handle aborted connections by first closing and disposing of the current MessageWebSocket object (as it is now useless), and then performing whatever other steps are appropriate for your app, such as creating a new MessageWebSocket and trying to connect again.

MessageReceived MessageReceived MessageReceived

An event that indicates that a message was received on the MessageWebSocket object.

public event TypedEventHandler MessageReceivedpublic event TypedEventHandler MessageReceivedPublic Event MessageReceived


All message processing and connection related errors are communicated through the GetDataReader and GetDataStream methods. If either of these methods throws an exception, it indicates that either the underlying connection is broken, or the server has sent invalid data, such as corrupt HTTP headers or a message that exceeds the maximum message size. The appropriate action for your code to take in the face of an exception from these methods is to re-establish a known good state by closing the websocket, creating a new one, and reconnecting to the server.

An empty message results in GetDataReader returning a valid IDataReader instance with UnconsumedBufferLength set to 0. GetDataStream returns a valid IInputStream instance that yields zero bytes.

ServerCustomValidationRequested ServerCustomValidationRequested ServerCustomValidationRequested

Occurs when a new MessageWebSocket connection to a secured server URI (wss: protocol) is being validated. Handle this event if you want to implement custom server validation for the connection.

public event TypedEventHandler ServerCustomValidationRequestedpublic event TypedEventHandler ServerCustomValidationRequestedPublic Event ServerCustomValidationRequested


Note that this event is raised after the default OS validation has been performed successfully, and that the default OS validation includes taking the IgnorableServerCertificateErrors control option into account.

Use the WebSocketServerCustomValidationRequestedEventArgs properties to access the server certificate and intermediate certificates being offered for validation.

In order to ensure proper completion, if your custom validation process involves any async operations, be sure to use the WebSocketServerCustomValidationRequestedEventArgs.GetDeferral method to get a deferral object that your event handler holds for the duration of the validation operation. When your validation is complete, you must call Deferral.Complete whether you accept or reject validation.

As an example of the kind of validation you can do in this event handler: you could compare the server certificate to a locally stored trusted certificate that matches the expected server certificate. In your event handler, you would compare the SHA-256 hash of the local certificate to the hash of the server certificate. If the hash values match, then the certificates are assumed to match, and server validation should succeed. If the hash values don't match, then the certificates don't match and validation should fail.

To indicate validation failure, call the WebSocketServerCustomValidationRequestedEventArgs.Reject method. To indicate validation success, simply return from the event handler.

Note that whether validation succeeds or fails, you must call Deferral.Complete on the deferral object you acquired when you started the validation process.

See Also