Share via


How to connect with a MessageWebSocket (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This topic will show you how to send and receive whole messages of data using MessageWebSocket in a Windows Runtime app.

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.

A MessageWebSocket is typically used in scenarios where messages are not very large. Both UTF-8 and binary files are supported. For UTF-8 messages, MessageWebSocket must be used. since StreamWebSocket only supports binary messages.

Prerequisites

The following examples use JavaScript and are based on the WebSocket sample. For general help creating a Windows Runtime app using JavaScript, see Create your first Windows Runtime app using JavaScript. Additionally, JavaScript promises are used in this topic to complete asynchronous operations. For more information on this programming pattern, see Asynchronous programming in JavaScript using promises.

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.

Note  On Windows Phone, there is only one network capability (Internet (Client & Server))which enables all network access for the app.

 

For more information, see How to set network capabilities.

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.

Note  You may wish to display messages to the user or log that certain events have happened (for example, when a connection is made or when an error occurs).

 

  • Open the js folder. Open your .js file and add the following code.

    function startSend() {
       if (!messageWebSocket) {
          var webSocket = new Windows.Networking.Sockets.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 = Windows.Networking.Sockets.SocketMessageType.utf8;
          // Set up callbacks
          webSocket.onmessagereceived = onMessageReceived;
          webSocket.onclosed = onClosed;
    
          var serverAddress = new Windows.Foundation.Uri(document.getElementById("serverAddress").value);
    
          try {
             webSocket.connectAsync(serverAddress).done(function () {
             messageWebSocket = webSocket;
             // The default DataWriter encoding is utf8.
             messageWriter = new Windows.Storage.Streams.DataWriter(webSocket.outputStream);
             messageWriter.writeString(document.getElementById("inputField").value);
             messageWriter.storeAsync().done("", sendError);
    
          }, function (error) {
             // The connection failed; add your own code to log or display 
             // the error, or take a specific action.
             });
          } catch (error) {
             // An error occurred while trying to connect; add your own code to  
             // log or display the error, or take a specific action.
          }
    
       }
       else {
          // The connection already exists; go ahead and send the message.
          messageWriter.writeString(document.getElementById("inputField").value);
          messageWriter.storeAsync().done("", sendError);          
       }
    }
    

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 .js file.

    function onMessageReceived(args) {
       // The incoming message is already buffered.
       var dataReader = args.getDataReader();
       // Use the dataReader to read data from the received message
    }
    

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 .js file.

    function onClosed(args) {
       // You can add code to log or display the code and reason
       // for the closure (stored in args.code and args.reason)
       if (messageWebSocket) {
          messageWebSocket.close();
       }
       messageWebSocket = null;
    }
    

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.

Other

Asynchronous programming in JavaScript using promises

Connecting with WebSockets

Create your first Windows Runtime app using JavaScript

How to connect with a StreamWebSocket

How to handle exceptions in network apps

How to set network capabilities

Reference

MessageWebSocket

Windows.Networking.Sockets

Samples

WebSocket sample