TriggeredConnectionStateChangedEventArgs TriggeredConnectionStateChangedEventArgs TriggeredConnectionStateChangedEventArgs TriggeredConnectionStateChangedEventArgs Class

Contains properties that the TriggeredConnectionStateChanged event passes to an application.

Syntax

Declaration

public sealed class TriggeredConnectionStateChangedEventArgspublic sealed class TriggeredConnectionStateChangedEventArgsPublic NotInheritable Class TriggeredConnectionStateChangedEventArgspublic sealed class TriggeredConnectionStateChangedEventArgs

Remarks

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 summary

Gets the unique identifier for the connection in progress.

Gets the @Windows.Networking.Sockets.StreamSocket.#ctor instance for the connection.

Gets the state of the connection in progress.

Properties

  • Id
    Id
    Id
    Id

    Gets the unique identifier for the connection in progress.

    public uint Id { get; }public uint Id { get; }Public ReadOnly Property Id As uintpublic uint Id { get; }

    Property Value

    • uint
      uint
      uint
      uint

      The unique identifier for the connection in progress.

  • Socket
    Socket
    Socket
    Socket

    Gets the @Windows.Networking.Sockets.StreamSocket.#ctor instance for the connection.

    public StreamSocket Socket { get; }public StreamSocket Socket { get; }Public ReadOnly Property Socket As StreamSocketpublic StreamSocket Socket { get; }

    Property Value

    Remarks

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

    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
    
  • 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 TriggeredConnectStatepublic TriggeredConnectState State { get; }

    Property Value

    Remarks

    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
    

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Capabilities

ID_CAP_PROXIMITY [Windows Phone] ID_CAP_PROXIMITY [Windows Phone]
proximity

Attributes

Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute

Details

Assembly

Windows.Networking.Proximity.dll