TriggeredConnectionStateChangedEventArgs TriggeredConnectionStateChangedEventArgs TriggeredConnectionStateChangedEventArgs TriggeredConnectionStateChangedEventArgs Class

Definition

Contains properties that the TriggeredConnectionStateChanged event passes to an application.

public : sealed class TriggeredConnectionStateChangedEventArgs : ITriggeredConnectionStateChangedEventArgspublic sealed class TriggeredConnectionStateChangedEventArgs : ITriggeredConnectionStateChangedEventArgsPublic NotInheritable Class TriggeredConnectionStateChangedEventArgs Implements ITriggeredConnectionStateChangedEventArgs// You can use this class in JavaScript.
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0 - for Xbox, see UWP features that aren't yet supported on Xbox)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_PROXIMITY [Windows Phone] proximity ID_CAP_PROXIMITY [Windows Phone]

Examples

// Click event for "Start" button.

private void StartFindingPeersButton_Click(object sender, RoutedEventArgs e)
{
    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
    {
        Windows.Networking.Proximity.PeerFinder.Start();

        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged += 
            TriggeredConnectionStateChanged;

        WriteMessageText("Waiting for peers. Enter proximity to connect. " +
      "Call PeerFinder.start() on the peer to send and receive messages.\n");
    }
    else {
        WriteMessageText("Peer discovery using tapping is not supported.\n");
    }
}

private void TriggeredConnectionStateChanged(object sender,
    Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
{
    if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
    {
        WriteMessageText("Connected. You may now send a message.\n");
        SendMessage(e.Socket);
    }
}

Windows.Networking.Sockets.StreamSocket proximitySocket;
Windows.Storage.Streams.DataWriter dataWriter;

// Reference socket streams for writing and reading messages.
private void SendMessage(Windows.Networking.Sockets.StreamSocket socket) {
    // Get the network socket from the proximity connection.
    proximitySocket = socket;

    // Create DataWriter for writing messages to peers.
    dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream);

    // Listen for messages from peers.
    Windows.Storage.Streams.DataReader dataReader = 
            new Windows.Storage.Streams.DataReader(proximitySocket.InputStream);
    StartReader(proximitySocket, dataReader);
}

// Send a message to the socket.
private async void SendMessageText() {
    string msg = SendMessageTextBlock.Text;

    if (msg.Length > 0) {
        var msgLength = dataWriter.MeasureString(msg);
        dataWriter.WriteInt32(msg.Length);
        dataWriter.WriteString(msg);
        try
        {
            await dataWriter.StoreAsync();
            WriteMessageText("Message sent: " + msg  + "\n");
        }
        catch (Exception e)
        {
            WriteMessageText("Send error: " + e.Message + "\n");
        }
    }
}

// Read out and print the message received from the socket.
private async void StartReader(
    Windows.Networking.Sockets.StreamSocket socket, 
    Windows.Storage.Streams.DataReader reader)
{
    uint initialLength = 4;

    try
    {
        await reader.LoadAsync(initialLength);
        uint msgLength = (uint)reader.ReadInt32();

        try
        {
            await reader.LoadAsync(msgLength);
            string message = reader.ReadString(msgLength);
            WriteMessageText("Received message: " + message + "\n");

            // After receiving a message, listen for the next message.
            StartReader(socket, reader);
        }
        catch (Exception e)
        {
            WriteMessageText("Error: " + e.Message + "\n");
            socket.Dispose();
        }
    }
    catch (Exception e)
    {
        WriteMessageText("Error: " + e.Message + "\n");
        socket.Dispose();
    }
}

// Write a message to MessageBlock on the UI thread.
private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.Current.CoreWindow.Dispatcher;

async private void WriteMessageText(string message, bool overwrite = false)
{
    await messageDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
            if (overwrite)
                MessageBlock.Text = message;
            else
                MessageBlock.Text += message;
        });
}
  function id(elementId) {
      return document.getElementById(elementId);
  }
  
  // Click event for "Start" button.
  function startFindingPeers() {
      if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
          Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {

          Windows.Networking.Proximity.PeerFinder.start();

          Windows.Networking.Proximity.PeerFinder.addEventListener(
"triggeredconnectionstatechanged", triggeredConnectionStateChanged);

          id("messageDiv").innerHTML += 
"Waiting for peers. Enter proximity to connect. " +
"Call PeerFinder.start() on the peer to send and receive messages.<br />";
      }
      else {
          id("messageDiv").innerHTML += 
"Peer discovery using tapping is not supported.<br />";
      }

  }

  function triggeredConnectionStateChanged(e) {
      if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
          id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
          sendMessage(e.socket);
      }
  }

  var proximitySocket;
  var dataWriter;

  // Reference socket streams for writing and reading messages.
  function sendMessage(socket) {
      id("sendMessageButton").addEventListener("click", sendMessageText);

      // Get the network socket from the proximity connection.
      proximitySocket = socket;

      // Create DataWriter for writing messages to peers.
      dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.outputStream);
              
      // Listen for messages from peers.
      var dataReader = new Windows.Storage.Streams.DataReader(proximitySocket.inputStream);
      startReader(proximitySocket, dataReader);
  }

  // Send a message to the socket.
  function sendMessageText() {        
      var msg = id("sendMessageText").value;
      
      if (msg.length > 0) {
          var msgLength = dataWriter.measureString(msg);
          dataWriter.writeInt32(msgLength);
          dataWriter.writeString(msg);
          dataWriter.storeAsync().done(
              function (byteCount) {
                  id("messageDiv").innerHTML += "Message sent: " + msg.value + "<br />";
              },
              function (err) {
                  id("messageDiv").innerHTML += "Send error: " + err.message + "<br />";
              });
      }
  }

  // Read out and print the message received from the socket.
  function startReader(socket, reader) {
      var initialLength = 4; 
      reader.loadAsync(initialLength).done(
      function () {
          var msgLength = reader.readInt32();
          reader.loadAsync(msgLength).done(
              function () {
                  var message = reader.readString(msgLength);
                  id("messageDiv").innerHTML += "Received message: " + message + "<br />";

                  // After receiving a message, listen for the next message.
                  startReader(socket, reader);
              },
              function (err) {
                  id("messageDiv").innerHTML += "Error: " + err.message + "<br />";
                  socket.close();
              });
      },
      function (err) {
          id("messageDiv").innerHTML += "Error: " + err.message + "<br />";
          socket.close();
      });
  }
' Click event for "Start" button.

Private Sub StartFindingPeersButton_Click(sender As Object, e As RoutedEventArgs)

    If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then

        Windows.Networking.Proximity.PeerFinder.Start()

        AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
            AddressOf TriggeredConnectionStateChanged

        WriteMessageText("Waiting for peers. Enter proximity to connect. " &
            "Call PeerFinder.start() on the peer to send and receive messages." & vbTab)
    Else
        WriteMessageText("Peer discovery using tapping is not supported." & vbTab)
    End If
End Sub

Private Sub TriggeredConnectionStateChanged(sender As Object,
    e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)

    If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
        WriteMessageText("Connected. You may now send a message." & vbTab)
        SendMessage(e.Socket)
    End If
End Sub

Private proximitySocket As Windows.Networking.Sockets.StreamSocket
Private dataWriter As Windows.Storage.Streams.DataWriter

' Reference socket streams for writing and reading messages.
Private Sub SendMessage(socket As Windows.Networking.Sockets.StreamSocket)
    ' Get the network socket from the proximity connection.
    proximitySocket = socket

    ' Create DataWriter for writing messages to peers.
    dataWriter = New Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream)

    ' Listen for messages from peers.
    Dim dataReader = New Windows.Storage.Streams.DataReader(proximitySocket.InputStream)
    StartReader(proximitySocket, dataReader)
End Sub

' Send a message to the socket.
Private Async Sub SendMessageText()
    Dim msg = SendMessageTextBlock.Text

    If msg.Length > 0 Then
        Dim msgLength = dataWriter.MeasureString(msg)
        dataWriter.WriteInt32(msg.Length)
        dataWriter.WriteString(msg)
        Try
            Await dataWriter.StoreAsync()
            WriteMessageText("Message sent: " & msg & vbTab)
        Catch e As Exception
            WriteMessageText("Send error: " & e.Message & vbTab)
        End Try
    End If
End Sub

' Read out and print the message received from the socket.
Private Async Sub StartReader(
    socket As Windows.Networking.Sockets.StreamSocket,
    reader As Windows.Storage.Streams.DataReader)

    Dim initialLength As UInteger = 4

    Try
        Await reader.LoadAsync(initialLength)
        Dim msgLength = CType(reader.ReadInt32(), UInteger)

        Try
            Await reader.LoadAsync(msgLength)
            Dim message = reader.ReadString(msgLength)
            WriteMessageText("Received message: " & message & vbTab)

            ' After receiving a message, listen for the next message.
            StartReader(socket, reader)
        Catch e As Exception
            WriteMessageText("Error: " & e.Message & vbTab)
            socket.Dispose()
        End Try
    Catch e As Exception
        WriteMessageText("Error: " & e.Message & vbTab)
        socket.Dispose()
    End Try
End Sub

' Write a message to MessageBlock on the UI thread.
Private Async Sub WriteMessageText(message As String, Optional overwrite As Boolean = False)
    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            If overwrite Then
                MessageBlock.Text = message
            Else
                MessageBlock.Text &= message
            End If
        End Sub)
End Sub

Properties

Id Id Id Id

Gets the unique identifier for the connection in progress.

public : unsigned int Id { get; }public uint Id { get; }Public ReadOnly Property Id As uint// You can use this property in JavaScript.
Value
unsigned int uint uint uint

The unique identifier for the connection in progress.

Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0 - for Xbox, see UWP features that aren't yet supported on Xbox)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
proximity ID_CAP_PROXIMITY [Windows Phone]
See Also

Socket Socket Socket Socket

Gets the StreamSocket instance for the connection.

public : StreamSocket Socket { get; }public StreamSocket Socket { get; }Public ReadOnly Property Socket As StreamSocket// You can use this property in JavaScript.
Value
StreamSocket StreamSocket StreamSocket StreamSocket

The StreamSocket instance for the connection.

Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0 - for Xbox, see UWP features that aren't yet supported on Xbox)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_PROXIMITY [Windows Phone] proximity ID_CAP_PROXIMITY [Windows Phone]

Examples

// Click event for "Start" button.

private void StartFindingPeersButton_Click(object sender, RoutedEventArgs e)
{
    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
    {
        Windows.Networking.Proximity.PeerFinder.Start();

        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged += 
            TriggeredConnectionStateChanged;

        WriteMessageText("Waiting for peers. Enter proximity to connect. " +
      "Call PeerFinder.start() on the peer to send and receive messages.
"); } else { WriteMessageText("Peer discovery using tapping is not supported.
"); } } private void TriggeredConnectionStateChanged(object sender, Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e) { if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed) { WriteMessageText("Connected. You may now send a message.
"); SendMessage(e.Socket); } } Windows.Networking.Sockets.StreamSocket proximitySocket; Windows.Storage.Streams.DataWriter dataWriter; // Reference socket streams for writing and reading messages. private void SendMessage(Windows.Networking.Sockets.StreamSocket socket) { // Get the network socket from the proximity connection. proximitySocket = socket; // Create DataWriter for writing messages to peers. dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream); // Listen for messages from peers. Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(proximitySocket.InputStream); StartReader(proximitySocket, dataReader); } // Send a message to the socket. private async void SendMessageText() { string msg = SendMessageTextBlock.Text; if (msg.Length > 0) { var msgLength = dataWriter.MeasureString(msg); dataWriter.WriteInt32(msg.Length); dataWriter.WriteString(msg); try { await dataWriter.StoreAsync(); WriteMessageText("Message sent: " + msg + "
"); } catch (Exception e) { WriteMessageText("Send error: " + e.Message + "
"); } } } // Read out and print the message received from the socket. private async void StartReader( Windows.Networking.Sockets.StreamSocket socket, Windows.Storage.Streams.DataReader reader) { uint initialLength = 4; try { await reader.LoadAsync(initialLength); uint msgLength = (uint)reader.ReadInt32(); try { await reader.LoadAsync(msgLength); string message = reader.ReadString(msgLength); WriteMessageText("Received message: " + message + "
"); // After receiving a message, listen for the next message. StartReader(socket, reader); } catch (Exception e) { WriteMessageText("Error: " + e.Message + "
"); socket.Dispose(); } } catch (Exception e) { WriteMessageText("Error: " + e.Message + "
"); socket.Dispose(); } } // Write a message to MessageBlock on the UI thread. private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.Current.CoreWindow.Dispatcher; async private void WriteMessageText(string message, bool overwrite = false) { await messageDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (overwrite) MessageBlock.Text = message; else MessageBlock.Text += message; }); }
  function id(elementId) {
      return document.getElementById(elementId);
  }
  
  // Click event for "Start" button.
  function startFindingPeers() {
      if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
          Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {

          Windows.Networking.Proximity.PeerFinder.start();

          Windows.Networking.Proximity.PeerFinder.addEventListener(
"triggeredconnectionstatechanged", triggeredConnectionStateChanged);

          id("messageDiv").innerHTML += 
"Waiting for peers. Enter proximity to connect. " +
"Call PeerFinder.start() on the peer to send and receive messages.<br />";
      }
      else {
          id("messageDiv").innerHTML += 
"Peer discovery using tapping is not supported.<br />";
      }

  }

  function triggeredConnectionStateChanged(e) {
      if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
          id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
          sendMessage(e.socket);
      }
  }

  var proximitySocket;
  var dataWriter;

  // Reference socket streams for writing and reading messages.
  function sendMessage(socket) {
      id("sendMessageButton").addEventListener("click", sendMessageText);

      // Get the network socket from the proximity connection.
      proximitySocket = socket;

      // Create DataWriter for writing messages to peers.
      dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.outputStream);
              
      // Listen for messages from peers.
      var dataReader = new Windows.Storage.Streams.DataReader(proximitySocket.inputStream);
      startReader(proximitySocket, dataReader);
  }

  // Send a message to the socket.
  function sendMessageText() {        
      var msg = id("sendMessageText").value;
      
      if (msg.length > 0) {
          var msgLength = dataWriter.measureString(msg);
          dataWriter.writeInt32(msgLength);
          dataWriter.writeString(msg);
          dataWriter.storeAsync().done(
              function (byteCount) {
                  id("messageDiv").innerHTML += "Message sent: " + msg.value + "<br />";
              },
              function (err) {
                  id("messageDiv").innerHTML += "Send error: " + err.message + "<br />";
              });
      }
  }

  // Read out and print the message received from the socket.
  function startReader(socket, reader) {
      var initialLength = 4; 
      reader.loadAsync(initialLength).done(
      function () {
          var msgLength = reader.readInt32();
          reader.loadAsync(msgLength).done(
              function () {
                  var message = reader.readString(msgLength);
                  id("messageDiv").innerHTML += "Received message: " + message + "<br />";

                  // After receiving a message, listen for the next message.
                  startReader(socket, reader);
              },
              function (err) {
                  id("messageDiv").innerHTML += "Error: " + err.message + "<br />";
                  socket.close();
              });
      },
      function (err) {
          id("messageDiv").innerHTML += "Error: " + err.message + "<br />";
          socket.close();
      });
  }
' Click event for "Start" button.

Private Sub StartFindingPeersButton_Click(sender As Object, e As RoutedEventArgs)

    If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then

        Windows.Networking.Proximity.PeerFinder.Start()

        AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
            AddressOf TriggeredConnectionStateChanged

        WriteMessageText("Waiting for peers. Enter proximity to connect. " &
            "Call PeerFinder.start() on the peer to send and receive messages." & vbTab)
    Else
        WriteMessageText("Peer discovery using tapping is not supported." & vbTab)
    End If
End Sub

Private Sub TriggeredConnectionStateChanged(sender As Object,
    e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)

    If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
        WriteMessageText("Connected. You may now send a message." & vbTab)
        SendMessage(e.Socket)
    End If
End Sub

Private proximitySocket As Windows.Networking.Sockets.StreamSocket
Private dataWriter As Windows.Storage.Streams.DataWriter

' Reference socket streams for writing and reading messages.
Private Sub SendMessage(socket As Windows.Networking.Sockets.StreamSocket)
    ' Get the network socket from the proximity connection.
    proximitySocket = socket

    ' Create DataWriter for writing messages to peers.
    dataWriter = New Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream)

    ' Listen for messages from peers.
    Dim dataReader = New Windows.Storage.Streams.DataReader(proximitySocket.InputStream)
    StartReader(proximitySocket, dataReader)
End Sub

' Send a message to the socket.
Private Async Sub SendMessageText()
    Dim msg = SendMessageTextBlock.Text

    If msg.Length > 0 Then
        Dim msgLength = dataWriter.MeasureString(msg)
        dataWriter.WriteInt32(msg.Length)
        dataWriter.WriteString(msg)
        Try
            Await dataWriter.StoreAsync()
            WriteMessageText("Message sent: " & msg & vbTab)
        Catch e As Exception
            WriteMessageText("Send error: " & e.Message & vbTab)
        End Try
    End If
End Sub

' Read out and print the message received from the socket.
Private Async Sub StartReader(
    socket As Windows.Networking.Sockets.StreamSocket,
    reader As Windows.Storage.Streams.DataReader)

    Dim initialLength As UInteger = 4

    Try
        Await reader.LoadAsync(initialLength)
        Dim msgLength = CType(reader.ReadInt32(), UInteger)

        Try
            Await reader.LoadAsync(msgLength)
            Dim message = reader.ReadString(msgLength)
            WriteMessageText("Received message: " & message & vbTab)

            ' After receiving a message, listen for the next message.
            StartReader(socket, reader)
        Catch e As Exception
            WriteMessageText("Error: " & e.Message & vbTab)
            socket.Dispose()
        End Try
    Catch e As Exception
        WriteMessageText("Error: " & e.Message & vbTab)
        socket.Dispose()
    End Try
End Sub

' Write a message to MessageBlock on the UI thread.
Private Async Sub WriteMessageText(message As String, Optional overwrite As Boolean = False)
    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            If overwrite Then
                MessageBlock.Text = message
            Else
                MessageBlock.Text &= message
            End If
        End Sub)
End Sub

Remarks

The Socket property is null until a successful connection has been completed. When a successful connection is completed, State equals Completed.

See Also

State State State State

Gets the state of the connection in progress.

public : TriggeredConnectState State { get; }public TriggeredConnectState State { get; }Public ReadOnly Property State As TriggeredConnectState// You can use this property in JavaScript.
Additional features and requirements
Device family
Windows 10 (introduced v10.0.10240.0 - for Xbox, see UWP features that aren't yet supported on Xbox)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)
Capabilities
ID_CAP_PROXIMITY [Windows Phone] proximity ID_CAP_PROXIMITY [Windows Phone]

Examples

// Click event for "Start" button.

private void StartFindingPeersButton_Click(object sender, RoutedEventArgs e)
{
    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
    {
        Windows.Networking.Proximity.PeerFinder.Start();

        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged += 
            TriggeredConnectionStateChanged;

        WriteMessageText("Waiting for peers. Enter proximity to connect. " +
      "Call PeerFinder.start() on the peer to send and receive messages.
"); } else { WriteMessageText("Peer discovery using tapping is not supported.
"); } } private void TriggeredConnectionStateChanged(object sender, Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e) { if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed) { WriteMessageText("Connected. You may now send a message.
"); SendMessage(e.Socket); } } Windows.Networking.Sockets.StreamSocket proximitySocket; Windows.Storage.Streams.DataWriter dataWriter; // Reference socket streams for writing and reading messages. private void SendMessage(Windows.Networking.Sockets.StreamSocket socket) { // Get the network socket from the proximity connection. proximitySocket = socket; // Create DataWriter for writing messages to peers. dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream); // Listen for messages from peers. Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(proximitySocket.InputStream); StartReader(proximitySocket, dataReader); } // Send a message to the socket. private async void SendMessageText() { string msg = SendMessageTextBlock.Text; if (msg.Length > 0) { var msgLength = dataWriter.MeasureString(msg); dataWriter.WriteInt32(msg.Length); dataWriter.WriteString(msg); try { await dataWriter.StoreAsync(); WriteMessageText("Message sent: " + msg + "
"); } catch (Exception e) { WriteMessageText("Send error: " + e.Message + "
"); } } } // Read out and print the message received from the socket. private async void StartReader( Windows.Networking.Sockets.StreamSocket socket, Windows.Storage.Streams.DataReader reader) { uint initialLength = 4; try { await reader.LoadAsync(initialLength); uint msgLength = (uint)reader.ReadInt32(); try { await reader.LoadAsync(msgLength); string message = reader.ReadString(msgLength); WriteMessageText("Received message: " + message + "
"); // After receiving a message, listen for the next message. StartReader(socket, reader); } catch (Exception e) { WriteMessageText("Error: " + e.Message + "
"); socket.Dispose(); } } catch (Exception e) { WriteMessageText("Error: " + e.Message + "
"); socket.Dispose(); } } // Write a message to MessageBlock on the UI thread. private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.Current.CoreWindow.Dispatcher; async private void WriteMessageText(string message, bool overwrite = false) { await messageDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (overwrite) MessageBlock.Text = message; else MessageBlock.Text += message; }); }
  function id(elementId) {
      return document.getElementById(elementId);
  }
  
  // Click event for "Start" button.
  function startFindingPeers() {
      if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
          Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {

          Windows.Networking.Proximity.PeerFinder.start();

          Windows.Networking.Proximity.PeerFinder.addEventListener(
"triggeredconnectionstatechanged", triggeredConnectionStateChanged);

          id("messageDiv").innerHTML += 
"Waiting for peers. Enter proximity to connect. " +
"Call PeerFinder.start() on the peer to send and receive messages.<br />";
      }
      else {
          id("messageDiv").innerHTML += 
"Peer discovery using tapping is not supported.<br />";
      }

  }

  function triggeredConnectionStateChanged(e) {
      if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
          id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
          sendMessage(e.socket);
      }
  }

  var proximitySocket;
  var dataWriter;

  // Reference socket streams for writing and reading messages.
  function sendMessage(socket) {
      id("sendMessageButton").addEventListener("click", sendMessageText);

      // Get the network socket from the proximity connection.
      proximitySocket = socket;

      // Create DataWriter for writing messages to peers.
      dataWriter = new Windows.Storage.Streams.DataWriter(proximitySocket.outputStream);
              
      // Listen for messages from peers.
      var dataReader = new Windows.Storage.Streams.DataReader(proximitySocket.inputStream);
      startReader(proximitySocket, dataReader);
  }

  // Send a message to the socket.
  function sendMessageText() {        
      var msg = id("sendMessageText").value;
      
      if (msg.length > 0) {
          var msgLength = dataWriter.measureString(msg);
          dataWriter.writeInt32(msgLength);
          dataWriter.writeString(msg);
          dataWriter.storeAsync().done(
              function (byteCount) {
                  id("messageDiv").innerHTML += "Message sent: " + msg.value + "<br />";
              },
              function (err) {
                  id("messageDiv").innerHTML += "Send error: " + err.message + "<br />";
              });
      }
  }

  // Read out and print the message received from the socket.
  function startReader(socket, reader) {
      var initialLength = 4; 
      reader.loadAsync(initialLength).done(
      function () {
          var msgLength = reader.readInt32();
          reader.loadAsync(msgLength).done(
              function () {
                  var message = reader.readString(msgLength);
                  id("messageDiv").innerHTML += "Received message: " + message + "<br />";

                  // After receiving a message, listen for the next message.
                  startReader(socket, reader);
              },
              function (err) {
                  id("messageDiv").innerHTML += "Error: " + err.message + "<br />";
                  socket.close();
              });
      },
      function (err) {
          id("messageDiv").innerHTML += "Error: " + err.message + "<br />";
          socket.close();
      });
  }
' Click event for "Start" button.

Private Sub StartFindingPeersButton_Click(sender As Object, e As RoutedEventArgs)

    If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then

        Windows.Networking.Proximity.PeerFinder.Start()

        AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
            AddressOf TriggeredConnectionStateChanged

        WriteMessageText("Waiting for peers. Enter proximity to connect. " &
            "Call PeerFinder.start() on the peer to send and receive messages." & vbTab)
    Else
        WriteMessageText("Peer discovery using tapping is not supported." & vbTab)
    End If
End Sub

Private Sub TriggeredConnectionStateChanged(sender As Object,
    e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)

    If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
        WriteMessageText("Connected. You may now send a message." & vbTab)
        SendMessage(e.Socket)
    End If
End Sub

Private proximitySocket As Windows.Networking.Sockets.StreamSocket
Private dataWriter As Windows.Storage.Streams.DataWriter

' Reference socket streams for writing and reading messages.
Private Sub SendMessage(socket As Windows.Networking.Sockets.StreamSocket)
    ' Get the network socket from the proximity connection.
    proximitySocket = socket

    ' Create DataWriter for writing messages to peers.
    dataWriter = New Windows.Storage.Streams.DataWriter(proximitySocket.OutputStream)

    ' Listen for messages from peers.
    Dim dataReader = New Windows.Storage.Streams.DataReader(proximitySocket.InputStream)
    StartReader(proximitySocket, dataReader)
End Sub

' Send a message to the socket.
Private Async Sub SendMessageText()
    Dim msg = SendMessageTextBlock.Text

    If msg.Length > 0 Then
        Dim msgLength = dataWriter.MeasureString(msg)
        dataWriter.WriteInt32(msg.Length)
        dataWriter.WriteString(msg)
        Try
            Await dataWriter.StoreAsync()
            WriteMessageText("Message sent: " & msg & vbTab)
        Catch e As Exception
            WriteMessageText("Send error: " & e.Message & vbTab)
        End Try
    End If
End Sub

' Read out and print the message received from the socket.
Private Async Sub StartReader(
    socket As Windows.Networking.Sockets.StreamSocket,
    reader As Windows.Storage.Streams.DataReader)

    Dim initialLength As UInteger = 4

    Try
        Await reader.LoadAsync(initialLength)
        Dim msgLength = CType(reader.ReadInt32(), UInteger)

        Try
            Await reader.LoadAsync(msgLength)
            Dim message = reader.ReadString(msgLength)
            WriteMessageText("Received message: " & message & vbTab)

            ' After receiving a message, listen for the next message.
            StartReader(socket, reader)
        Catch e As Exception
            WriteMessageText("Error: " & e.Message & vbTab)
            socket.Dispose()
        End Try
    Catch e As Exception
        WriteMessageText("Error: " & e.Message & vbTab)
        socket.Dispose()
    End Try
End Sub

' Write a message to MessageBlock on the UI thread.
Private Async Sub WriteMessageText(message As String, Optional overwrite As Boolean = False)
    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            If overwrite Then
                MessageBlock.Text = message
            Else
                MessageBlock.Text &= message
            End If
        End Sub)
End Sub
See Also

See Also