Compartir a través de


How to connect with a StreamWebSocket (XAML)

This topic will show you how to enable a Windows Store app to send and receive sections of a message with a StreamWebSocket. This type of WebSocket object enables notifications when a complete message has been transferred. StreamWebSockets are typically used in scenarios where large files are being transferred between a client and server which support WebSockets.

Prerequisites

The following examples use C# and are based on the Connecting with WebSockets sample. For help creating your first app, see Create your first Windows Store app using C# or Visual Basic.

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.

Instructions

1. Create a StreamWebSocket object to send and receive data

The code in this section creates a new StreamWebSocket, connects to a WebSocket server, sends data to the server, and listens for a response.

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).

 

Note  The ReceiveData() and SendData() functions to perform the write and read operations will be defined in subsequent steps.

 

  • Open the CS folder. Open the .cs file you are using and add the following code.

    private StreamWebSocket streamWebSocket;
    private byte[] readBuffer;
    
    private async void Start_Click(object sender, RoutedEventArgs e)
       {
          try
          {
             // Make a local copy to avoid races with the Closed event.
             StreamWebSocket webSocket = streamWebSocket;
             // Have we connected yet?
             if (webSocket == null)
               {
                  Uri server = new Uri(ServerAddressField.Text.Trim());
    
                  webSocket = new StreamWebSocket();
                  webSocket.Closed += Closed;
    
                  await webSocket.ConnectAsync(server);
                  streamWebSocket = webSocket; // Only store it after successfully connecting.
    
                  readBuffer = new byte[1000];
    
                  // Start a background task to continuously read for incoming data
                  Task receiving = Task.Factory.StartNew(ReceiveData,
                     webSocket.InputStream.AsStreamForRead(), TaskCreationOptions.LongRunning);
    
                  // Start a background task to continuously write outgoing data
                  Task sending = Task.Factory.StartNew(SendData,
                     webSocket.OutputStream, TaskCreationOptions.LongRunning);
                }
            }
            catch (Exception ex) // For debugging
            {
               WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
               // Add your specific error-handling code here.
            }
       }
    

2. Write the function for sending data

The code in this section lets your WebSocket object send data to a server.

  • Add the following code to your .cs file to define the SendData() function.

    private async void SendData(object state)
       {
          int dataSent = 0;
          byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09};
    
          try
          {
             IOutputStream writeStream = (IOutputStream)state;
    
                // Send until the socket gets closed/stopped
                while (true)
                {
                   // using System.Runtime.InteropServices.WindowsRuntime;
                   await writeStream.WriteAsync(data.AsBuffer());
    
                   dataSent += data.Length;
    
                   MarshalText(DataSentField, dataSent.ToString(), false);
    
                   // Delay so the user can watch what's going on.
                   await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch (ObjectDisposedException)
            {
               // Display a message that the write has stopped, or take a specific action
            }
            catch (Exception ex)
            {
               WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
               // Add your specific error-handling code here.
            }
       }
    

3. Write the function for reading data

The code in this section lets your WebSocket object read data from a server.

  • Add the following code to your .cs file to define the ReceiveData() function.

    private async void ReceiveData(object state)
       {
          int bytesReceived = 0;
          try
          {
             Stream readStream = (Stream)state;
    
             while (true) // Until closed and ReadAsync fails.
             {
                int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                bytesReceived += read;
                MarshalText(DataReceivedField, bytesReceived.ToString(), false);
    
                // Do something with the data.
             }
          }
          catch (ObjectDisposedException)
          {
             // Display a message that the read has stopped, or take a specific action
          }
          catch (Exception ex)
          {
             WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
             // Add your specific error-handling code here.
          }
       }
    

4. Register your callback for the StreamWebSocket.Closed event

When the StreamWebSocket.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/Stop/Reset methods.
          StreamWebSocket webSocket = Interlocked.Exchange(ref streamWebSocket, 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 StreamWebSocket.

For a complete sample that demonstrates how to send and receive data with WebSockets, see the WebSocket sample.

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 MessageWebSocket

How to use advanced WebSocket controls

How to secure WebSocket connections with TLS/SSL

Reference

MessageWebSocket

StreamWebSocket

Windows.Networking.Sockets

Samples

WebSocket sample