How to connect with a MessageWebSocket (XAML)
This topic will show you how to enable a Windows Store app to send and receive data by using a MessageWebSocket. This type of WebSocket object allows sections of a message to be read with each read operation. MessageWebSockets are typically used in scenarios where messages are not extremely large. Both UTF-8 and binary files are supported.
Prerequisites
The following examples use C# or C++ and are based on the WebSocket sample. For general help creating a Windows Runtime app using C# or Visual Basic, see Create your first Windows Runtime app using C# or Visual Basic. For general help creating a Windows Runtime app using C++, see Create your first Windows Runtime app using C++.
To ensure your Windows Runtime app is network ready, you must set any network capabilities that are needed in the project Package.appxmanifest file. If your app needs to connect as a client to remote services on the Internet, then the Internet (Client) capability is needed. If the app needs to connect as a client to remote services on a home network or work network, then the Home/Work Networking capability is needed.
Use a MessageWebSocket to send data
The code in this section creates a new MessageWebSocket, connects to a WebSocket server, and sends data to the server. Once a successful connection is established, the app waits for the MessageWebSocket.MessageReceived event to be invoked, indicating that data was received.
-
Open the CS folder. Open your .cs file and add the following code.
private MessageWebSocket messageWebSocket; private DataWriter messageWriter; private async void Start_Click(object sender, RoutedEventArgs e) { try { // Make a local copy to avoid races with Closed events. MessageWebSocket webSocket = messageWebSocket; // Have we connected yet? if (webSocket == null) { Uri server = new Uri(ServerAddressField.Text.Trim()); webSocket = new MessageWebSocket(); // MessageWebSocket supports both utf8 and binary messages. // When utf8 is specified as the messageType, then the developer // promises to only send utf8-encoded data. webSocket.Control.MessageType = SocketMessageType.Utf8; // Set up callbacks webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; // Only store it after successfully connecting. messageWriter = new DataWriter(webSocket.OutputStream); } string message = InputField.Text; // Buffer any data we want to send. messageWriter.WriteString(message); // Send the data as one complete message. await messageWriter.StoreAsync(); } catch (Exception ex) // For debugging { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add your specific error-handling code here. } }
Register your callback for the MessageWebSocket.MessageReceived event
When the MessageWebSocket.MessageReceived event occurs, the registered callback is called and receives data from MessageWebSocketMessageReceivedEventArgs.
-
Add the following code to your .cs file.
private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { using (DataReader reader = args.GetDataReader()) { reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; string read = reader.ReadString(reader.UnconsumedBufferLength); } } catch (Exception ex) // For debugging { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add your specific error-handling code here. } }
Register your callback for the MessageWebSocket.Closed event
When the MessageWebSocket.Closed event occurs, the registered callback is called and receives data from WebSocketClosedEventArgs to close the connection.
-
Add the following code to your .cs file.
private void Closed(IWebSocket sender, WebSocketClosedEventArgs args) { // You can add code to log or display the code and reason // for the closure (stored in args.Code and args.Reason) // This is invoked on another thread so use Interlocked // to avoid races with the Start/Close/Reset methods. MessageWebSocket webSocket = Interlocked.Exchange(ref messageWebSocket, null); if (webSocket != null) { webSocket.Dispose(); } }
Summary and next steps
In this tutorial, we reviewed how to connect to a WebSocket server and how to send and receive data using a MessageWebSocket.
For a complete sample that demonstrates how to send and receive data with WebSockets, see the WebSocket sample.
Related topics
- Other
- Connecting with WebSockets
- Create your first Windows Runtime app using C# or Visual Basic
- Create your first Windows Runtime app using C++
- How to configure network capabilities
- How to connect with a StreamWebSocket
- How to use advanced WebSocket controls
- How to secure WebSocket connections with TLS/SSL
- Reference
- MessageWebSocket
- StreamWebSocket
- Windows.Networking.Sockets
- Samples
- WebSocket sample