PeerFinder PeerFinder PeerFinder PeerFinder Class

Enables you to discover other instances of your app on nearby devices and create a socket connection between the peer apps by using a tap gesture or by browsing. For creating Bluetooth socket connections on Windows 8.1 and later, use Windows.Devices.Bluetooth.Rfcomm instead.

Syntax

Declaration

public static class PeerFinderpublic static class PeerFinderPublic Static Class PeerFinder

Remarks

Important

The Proximity APIs do not provide authentication. You should avoid exchanging sensitive data with these APIs.

Examples

var started = false;

// Click event for "Advertise" button.
function advertiseForPeers(launchedFromTap) {
    Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;

    if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
        Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {

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

        id("messageDiv").innerHTML +=
            "You can tap to connect a peer device that is " +
            "also advertising for a connection.<br />";
    } else {
        id("messageDiv").innerHTML +=
      "Tap to connect is not supported.<br />";
    }

    if (!launchedFromTap) {
        if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
              Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
            id("messageDiv").innerHTML +=
                "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }

    if (!started) {
        Windows.Networking.Proximity.PeerFinder.start();
        started = true;
    }
}

function triggeredConnectionStateChanged(e) {
    if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
        id("messageDiv").innerHTML +=
            "Peer found. You may now pull your devices out of proximity.<br />";
    }
    if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
        id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
        sendMessage(e.socket);
    }
}


// Click event for "Browse" button.
function findPeers() {
    if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
        Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {

        Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
    function (peerInfoCollection) {
        if (peerInfoCollection.length > 0) {
            // Connect to first peer found - example only.
            // In your app, provide the user with a list of available peers.
            connectToPeer(peerInfoCollection[0]);
        }
    },
    function (err) {
        id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
    });
    } else {
        id("messageDiv").innerHTML +=
  "Peer discovery using Wi-Fi Direct is not supported.<br />";
    }
}

function connectToPeer(peerInfo) {
    id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
    Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
        function (socket) {
            id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
            sendMessage(socket);
        },
        function (err) {
            id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
        });

    requestingPeer = null;
}

function stopFindingPeers() {
    Windows.Networking.Proximity.PeerFinder.stop();
    started = false;
    if (proximitySocket != null) { closeSocket(); }
}

// Handle external connection requests.
var requestingPeer;

function connectionRequested(e) {
    id("messageDiv").innerHTML +=
        "Connection requested by " + e.peerInformation.DisplayName + ". " +
        "Click 'Accept Connection' to connect.";
    requestingPeer = e.PeerInformation;
}

function acceptConnection() {
    if (requestingPeer == null) {
        id("messageDiv").innerHTML += "No peer connection has been requested.";
        return;
    }

    connectToPeer(requestingPeer);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
    Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;

    // If activated from launch or from the background, create a peer connection.
    var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
    if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
    {
        if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
        {
            AdvertiseForPeersButton_Click(null, null);
        }
    }
}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    if (_started)
    {
        // Detach the callback handler (there can only be one PeerConnectProgress handler).
        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
        // Detach the incoming connection request event handler.
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
        Windows.Networking.Proximity.PeerFinder.Stop();
        CloseSocket();
        _started = false;
    }
}

// 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;
        });
}

bool _started = false;

// Click event handler for "Advertise" button.
private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
{
    if (_started) 
    {
        WriteMessageText("You are already advertising for a connection.\n");
        return; 
    }

    Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;

    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
    {
        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
            TriggeredConnectionStateChanged;

        WriteMessageText("You can tap to connect a peer device that is " +
                         "also advertising for a connection.\n");
    }
    else
    {
        WriteMessageText("Tap to connect is not supported.\n");
    }

    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
    {
        WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
    }

   Windows.Networking.Proximity.PeerFinder.Start();
   _started = true;
}

private void TriggeredConnectionStateChanged(
    object sender,
    Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
{
    if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
    {
        WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
    }
    if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
    {
        WriteMessageText("Connected. You may now send a message.\n");
        SendMessage(e.Socket);
    }
}

// Click event handler for "Browse" button.
async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
{
    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
    {
        WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        return;
    }

    try
    {
        var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
        if (peerInfoCollection.Count > 0)
        {
            // Connect to first peer found - example only.
            // In your app, provide the user with a list of available peers.
            ConnectToPeer(peerInfoCollection[0]);
        }
    }
    catch (Exception err)
    {
        WriteMessageText("Error finding peers: " + err.Message + "\n");
    }
}

async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
{
    WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
    try
    {
        Windows.Networking.Sockets.StreamSocket socket =
            await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);

        WriteMessageText("Connection successful. You may now send messages.\n");
        SendMessage(socket);
    }
    catch (Exception err)
    {
        WriteMessageText("Connection failed: " + err.Message + "\n");
    }

    requestingPeer = null;
}

// Click event handler for "Stop" button.
private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
{
    _started = false;
    Windows.Networking.Proximity.PeerFinder.Stop();
    if (proximitySocket != null) { CloseSocket(); }
}

// Handle external connection requests.
Windows.Networking.Proximity.PeerInformation requestingPeer;

private void ConnectionRequested(object sender,
    Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
{
    requestingPeer = e.PeerInformation;
    WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
        "Click 'Accept Connection' to connect.");
}

private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
{
    if (requestingPeer == null)
    {
        WriteMessageText("No peer connection has been requested.");
        return;
    }

    ConnectToPeer(requestingPeer);
}
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
    DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
    AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested

    ' If activated from launch or from the background, create a peer connection.
    Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
    If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then

        If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
            AdvertiseForPeersButton_Click()
        End If
    End If
End Sub

Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
    If _started Then
        ' Detach the callback handler (there can only be one PeerConnectProgress handler).
        RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
        ' Detach the incoming connection request event handler.
        RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
        Windows.Networking.Proximity.PeerFinder.Stop()
        CloseSocket()
        _started = False
    End If
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

Private _started As Boolean = False

' Click event handler for "Advertise" button.
Private Sub AdvertiseForPeersButton_Click()

    If _started Then
        WriteMessageText("You are already advertising for a connection." & vbCrLf)
        Return
    End If

    Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text

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

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

        WriteMessageText("You can tap to connect a peer device that is " &
                         "also advertising for a connection." & vbCrLf)
    Else
        WriteMessageText("Tap to connect is not supported." & vbCrLf)
    End If

    If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
        Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
        Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then

        WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
    End If

    Windows.Networking.Proximity.PeerFinder.Start()
    _started = True
End Sub

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

    If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then

        WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
    End If

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

' Click event handler for "Browse" button.
Private Async Sub FindPeersButton_Click()
    If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
        Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
        Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then

        WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        Return
    End If

    Try
        Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
        If peerInfoCollection.Count > 0 Then
            ' Connect to first peer found - example only.
            ' In your app, provide the user with a list of available peers.
            ConnectToPeer(peerInfoCollection(0))
        End If
    Catch err As Exception
        WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
    End Try
End Sub

Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)

    WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
    Try
        Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)

        WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
        SendMessage(socket)
    Catch err As Exception
        WriteMessageText("Connection failed: " & err.Message & vbCrLf)
    End Try

    requestingPeer = Nothing
End Sub

' Click event handler for "Stop" button.
Private Sub StopFindingPeersButton_Click()

    _started = False
    Windows.Networking.Proximity.PeerFinder.Stop()
    If proximitySocket IsNot Nothing Then CloseSocket()
End Sub

' Handle external connection requests.
Private requestingPeer As Windows.Networking.Proximity.PeerInformation

Private Sub ConnectionRequested(sender As Object,
    e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)

    requestingPeer = e.PeerInformation

    WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
        "Click 'Accept Connection' to connect.")
End Sub

Private Sub AcceptConnectionButton_Click()
    If requestingPeer Is Nothing Then
        WriteMessageText("No peer connection has been requested.")
        Return
    End If

    ConnectToPeer(requestingPeer)
End Sub

Properties summary

Specifies whether the PeerFinder class may connect a @Windows.Networking.Sockets.StreamSocket.#ctor object by using Bluetooth.

Specifies whether the PeerFinder class may connect to a StreamSocket object using TCP/IP.

Specifies whether the PeerFinder class may connect a @Windows.Networking.Sockets.StreamSocket.#ctor object by using Wi-Fi Direct.

Gets a list of alternate appId values to match with peer applications on other platforms.

Gets or sets user or device data to include during device discovery.

Gets or sets the name that identifies your computer to remote peers.

Gets or sets the role of the app in peer-to-peer connections.

Gets a value that indicates which discovery options are available to use with the PeerFinder class.

Methods summary

Connects to a peer discovered by a call to the FindAllPeersAsync() method.

Creates a new instance of a PeerWatcher object for dynamic discovery of peer apps.

Asynchronously browses for peer devices that are running the same app within wireless range.

Makes an app discoverable to remote peers.

Makes an app discoverable to remote peers.

Stops advertising for a peer connection.

Events summary

Occurs when a remote peer requests a connection using the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method.

Occurs during a tap gesture from a remote peer.

Properties

  • AllowBluetooth
    AllowBluetooth
    AllowBluetooth
    AllowBluetooth

    Specifies whether the PeerFinder class may connect a @Windows.Networking.Sockets.StreamSocket.#ctor object by using Bluetooth.

    public static bool AllowBluetooth { get; set; }public static bool AllowBluetooth { get; set; }Public Static ReadWrite Property AllowBluetooth As bool

    Property Value

    • bool
      bool
      bool
      bool

      True if the PeerFinder class may connect a @Windows.Networking.Sockets.StreamSocket.#ctor object by using Bluetooth; otherwise false. The default is true.

  • AllowInfrastructure
    AllowInfrastructure
    AllowInfrastructure
    AllowInfrastructure

    Specifies whether the PeerFinder class may connect to a StreamSocket object using TCP/IP.

    public static bool AllowInfrastructure { get; set; }public static bool AllowInfrastructure { get; set; }Public Static ReadWrite Property AllowInfrastructure As bool

    Property Value

    • bool
      bool
      bool
      bool

      True if the PeerFinder class may connect to a StreamSocket object using TCP/IP; otherwise false.

  • AllowWiFiDirect
    AllowWiFiDirect
    AllowWiFiDirect
    AllowWiFiDirect

    Specifies whether the PeerFinder class may connect a @Windows.Networking.Sockets.StreamSocket.#ctor object by using Wi-Fi Direct.

    public static bool AllowWiFiDirect { get; set; }public static bool AllowWiFiDirect { get; set; }Public Static ReadWrite Property AllowWiFiDirect As bool

    Property Value

    • bool
      bool
      bool
      bool

      True if the PeerFinder class may connect a @Windows.Networking.Sockets.StreamSocket.#ctor object by using Wi-Fi Direct; otherwise false. The default is true.

    Remarks

    Setting the AllowWiFiDirect property to false disables the ability to browse for peer apps using Wi-Fi Direct. You will not be able to use the FindAllPeersAsync() method to browse for remote peers.

    Windows Phone 8

    Wi-Fi Direct is not supported on Windows Phone 8. For more information, see Proximity.

  • AlternateIdentities
    AlternateIdentities
    AlternateIdentities
    AlternateIdentities

    Gets a list of alternate appId values to match with peer applications on other platforms.

    public static IMap<string, string> AlternateIdentities { get; }public static IMap<string, string> AlternateIdentities { get; }Public Static ReadOnly Property AlternateIdentities As IMap<string, string>

    Property Value

    • A list of alternate appId values to match with peer applications on other platforms.

    Remarks

    The AlternateIdentities property is used to add alternate proximity app Ids that match the proximity app Ids of peer apps running on other platforms. The PeerFinder class uses the alternate app Ids to match a peer app running on a Windows 8 computer with a peer app running on another platform. For example, if you create an app for Windows 8 and also create the same app for Windows Phone, the apps will not have the same unique app Id on both platforms. You can use the PeerFinder class to match the peer apps by adding the app Id from the Windows Phone to the AlternateIdentities property of your Windows app, and by adding the app Id for your Windows app to the alternate identities of the Windows Phone.

    The other platform must also support adding alternate identities so that the proximity app Id can be specified on that platform. You must include the proximity app Id on the other platform for the PeerFinder class to connect your apps when tapping with a Windows device. The format of the alternate identity string for a specific platform is determined by the implementation of the other platform. For example, to get the correct alternate identity string for Windows Phone, refer to the Windows Phone proximity API documentation.

    The format of the proximity app Id is <package family name>!<app Id>. You can get the package family name from the FamilyName property. You must copy the app Id value from the Id attribute of the Application element in the package manifest for your app. For Example, PeerFinder.Add("WindowsPhone", "{1c6379c1-9d5e-4254-8f4c-be7ea24057d1}") adds a Windows Phone 8 app id as an alternate identity in your Windows 8 app. PeerFinder.Add("Windows", "b3c3e7ef-371a-464f-a75e-95ddbdcaf974_7fed2v891h66p!App") adds a Windows 8 app id as an alternate identity in a Windows Phone 8 app.

    Browsing within wireless range (FindAllPeersAsync)

    When you connect peer apps by browsing for devices within wireless range using the FindAllPeersAsync() method, you can only match one app Id at a time. By default peer matching when browsing uses the Windows 8 proximity app Id . You can browse to connect peer apps running on different platforms by adding a unique "browse" app Id to the AlternateIdentities property. You can then add that same "browse" app Id to your peer app on the other platforms. If the "browse" alternate identity strings match, then the PeerFinder class can find the peer apps when you call the FindAllPeersAsync() method.

  • DiscoveryData
    DiscoveryData
    DiscoveryData
    DiscoveryData

    Gets or sets user or device data to include during device discovery.

    public static IBuffer DiscoveryData { get; set; }public static IBuffer DiscoveryData { get; set; }Public Static ReadWrite Property DiscoveryData As IBuffer

    Property Value

    Remarks

    Windows Phone Store app: This property is not supported. Setting it has no effect and no data is returned from this property on a phone.

    Examples

    // Default to the peer role.
    Windows.Networking.Proximity.PeerRole appRole = Windows.Networking.Proximity.PeerRole.Peer;
    bool launchedByTap = false;
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        LaunchActivatedEventArgs launchArgs = e.Parameter as LaunchActivatedEventArgs;
    
        if (launchArgs.Arguments.Contains("Windows.Networking.Proximity.PeerFinder:StreamSocket"))
        {
            launchedByTap = true;
    
            if (launchArgs.Arguments.Contains("Role=Host"))
            {
                appRole = Windows.Networking.Proximity.PeerRole.Host;
            }
            else if (launchArgs.Arguments.Contains("Role=Client"))
            {
                appRole = Windows.Networking.Proximity.PeerRole.Client;
            }
            else
            {
                appRole = Windows.Networking.Proximity.PeerRole.Peer;
            }
        }
    }
    
    bool started = false;
    
    // Click event for "Advertise" button.
    void AdvertiseForPeers(object sender, RoutedEventArgs e)
    {
        if (!started)
        {
            Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
            if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
            {
                Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                    TriggeredConnectionStateChanged;
    
                WriteMessageText("You can tap to connect a peer device that is " +
                                 "also advertising for a connection.\n");
            }
            else
            {
                WriteMessageText("Tap to connect is not supported.\n");
            }
    
            if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
            {
                WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            }
    
            // Set the peer role selected by the user.  
            if (launchedByTap)
            {
                Windows.Networking.Proximity.PeerFinder.Role = appRole;
            }
            else
            {
                switch (GetRoleFromUser())
                {
                    case "Peer":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Peer;
                        break;
                    case "Host":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Host;
                        break;
                    case "Client":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Client;
                        break;
                }
            }
    
            // Set discoveryData property with user supplied text. 
            var discData = GetDiscoveryDataFromUser();
            var writer = new Windows.Storage.Streams.DataWriter(
                new Windows.Storage.Streams.InMemoryRandomAccessStream());
            writer.WriteString(discData);
            Windows.Networking.Proximity.PeerFinder.DiscoveryData =
                writer.DetachBuffer();
    
            Windows.Networking.Proximity.PeerFinder.Start();
            started = true;
        }
    }
    
    // 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;
            });
    }
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.ApplicationModel.Activation;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace Proximity_PeerWatcher
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class PeerRole : Page
        {
            public PeerRole()
            {
                this.InitializeComponent();
            }
    
            TextBox DisplayNameTextBox = new TextBox();
            TextBlock MessageBlock = new TextBlock();
    
            private void TriggeredConnectionStateChanged(
                object sender,
                Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
            {
                if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
                {
    
                }
                if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
                {
    
                }
            }
    
            private string GetDiscoveryDataFromUser()
            {
                return "";
            }
    
            private string GetRoleFromUser()
            {
                return "Peer";
            }
    
            // <SnippetPeerRole_CS>
            // Default to the peer role.
            Windows.Networking.Proximity.PeerRole appRole = Windows.Networking.Proximity.PeerRole.Peer;
            bool launchedByTap = false;
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                LaunchActivatedEventArgs launchArgs = e.Parameter as LaunchActivatedEventArgs;
    
                if (launchArgs.Arguments.Contains("Windows.Networking.Proximity.PeerFinder:StreamSocket"))
                {
                    launchedByTap = true;
    
                    if (launchArgs.Arguments.Contains("Role=Host"))
                    {
                        appRole = Windows.Networking.Proximity.PeerRole.Host;
                    }
                    else if (launchArgs.Arguments.Contains("Role=Client"))
                    {
                        appRole = Windows.Networking.Proximity.PeerRole.Client;
                    }
                    else
                    {
                        appRole = Windows.Networking.Proximity.PeerRole.Peer;
                    }
                }
            }
    
            bool started = false;
    
            // Click event for "Advertise" button.
            void AdvertiseForPeers(object sender, RoutedEventArgs e)
            {
                if (!started)
                {
                    Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
                    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
                    {
                        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                            TriggeredConnectionStateChanged;
    
                        WriteMessageText("You can tap to connect a peer device that is " +
                                         "also advertising for a connection.\n");
                    }
                    else
                    {
                        WriteMessageText("Tap to connect is not supported.\n");
                    }
    
                    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
                    {
                        WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
                    }
    
                    // Set the peer role selected by the user.  
                    if (launchedByTap)
                    {
                        Windows.Networking.Proximity.PeerFinder.Role = appRole;
                    }
                    else
                    {
                        switch (GetRoleFromUser())
                        {
                            case "Peer":
                                Windows.Networking.Proximity.PeerFinder.Role =
                                    Windows.Networking.Proximity.PeerRole.Peer;
                                break;
                            case "Host":
                                Windows.Networking.Proximity.PeerFinder.Role =
                                    Windows.Networking.Proximity.PeerRole.Host;
                                break;
                            case "Client":
                                Windows.Networking.Proximity.PeerFinder.Role =
                                    Windows.Networking.Proximity.PeerRole.Client;
                                break;
                        }
                    }
    
                    // Set discoveryData property with user supplied text. 
                    var discData = GetDiscoveryDataFromUser();
                    var writer = new Windows.Storage.Streams.DataWriter(
                        new Windows.Storage.Streams.InMemoryRandomAccessStream());
                    writer.WriteString(discData);
                    Windows.Networking.Proximity.PeerFinder.DiscoveryData =
                        writer.DetachBuffer();
    
                    Windows.Networking.Proximity.PeerFinder.Start();
                    started = true;
                }
            }
    
            // 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;
                    });
            }
            // </SnippetPeerRole_CS>
    
        }
    }
    
    // Default to the peer role.
    var appRole = Windows.Networking.Proximity.PeerRole.peer;
    var launchedFromTap = false; 
    
    app.onactivated = function (args) {
        if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            Windows.Networking.Proximity.PeerFinder.addEventListener("connectionrequested", connectionRequested);
    
            // Detect if app launched from a tap.
            if ((args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) &&
                (args.detail.arguments === "Windows.Networking.Proximity.PeerFinder:StreamSocket")) {
    
                launchedFromTap = true; 
    
                if (args.detail.arguments.search("Role=Host") !== -1) { 
                    appRole = Windows.Networking.Proximity.PeerRole.host; 
                } 
                else if (args.detail.arguments.search("Role=Client") !== -1) { 
                    appRole = Windows.Networking.Proximity.PeerRole.client; 
                } 
                else { 
                    appRole = Windows.Networking.Proximity.PeerRole.peer; 
                } 
            } 
        }
    
        advertiseForPeers(true);
    
        args.setPromise(WinJS.UI.processAll());
    }
    
    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
                "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }       
    
        if (!started) {
            // Set the peer role selected by the user.  
            if (launchedByTap) { 
                Windows.Networking.Proximity.PeerFinder.role = appRole; 
            } 
            else { 
                switch (getRoleFromUser()) { 
                    case "peer": 
                        Windows.Networking.Proximity.PeerFinder.role = 
                            Windows.Networking.Proximity.PeerRole.peer; 
                        break; 
                    case "host": 
                        Windows.Networking.Proximity.PeerFinder.role = 
                            Windows.Networking.Proximity.PeerRole.host; 
                        break; 
                    case "client": 
                        Windows.Networking.Proximity.PeerFinder.role = 
                            Windows.Networking.Proximity.PeerRole.client; 
                        break; 
                } 
            } 
    
            // Set discoveryData property with user supplied text. 
            var discData = getDiscoveryDataFromUser();
            var writer = Windows.Storage.Streams.DataWriter(
                new Windows.Storage.Streams.InMemoryRandomAccessStream()); 
            writer.writeString(discData); 
            Windows.Networking.Proximity.PeerFinder.discoveryData = 
                writer.detachBuffer(); 
    
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
  • DisplayName
    DisplayName
    DisplayName
    DisplayName

    Gets or sets the name that identifies your computer to remote peers.

    public static string DisplayName { get; set; }public static string DisplayName { get; set; }Public Static ReadWrite Property DisplayName As string

    Property Value

    • string
      string
      string
      string

      The name that identifies your computer to remote peers.

    Remarks

    Important

    Always set the DisplayName property to a unique value for your app before you call the Start(System.String) method.

    The DisplayName property value is included in the PeerInformation instance that's created when a remote peer calls the FindAllPeersAsync() method and finds your computer.

    If you don't specify a value for the DisplayName property, the computer name is used.

    The maximum length of DisplayName is 50 characters.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    
  • Role
    Role
    Role
    Role

    Gets or sets the role of the app in peer-to-peer connections.

    public static PeerRole Role { get; set; }public static PeerRole Role { get; set; }Public Static ReadWrite Property Role As PeerRole

    Property Value

    Remarks

    The Role property is used in multi-peer app connections to identify whether the peer app is the Host or Client, or if the peer app is participating in a two-peer connection as a Peer. For multi-peer app connections, you must set the Role property before calling the Start(System.String) method. If the Role property is not set, the default is Peer.

    In a multi-peer app scenario, the Role identifies the capability of the apps to connect. A Host app can connect to up to five Client apps. Host apps can only discover apps that advertise as Client apps. Client apps can only discover apps that advertise as Host apps. The Peer role identifies a two-app scenario. Therefore, Peer apps can only discover other Peer apps. The same rules apply for peer apps connected using a tap gesture. For example, apps advertising as Host apps can only tap to connect with apps advertising as Client apps.

    Examples

    // Default to the peer role.
    Windows.Networking.Proximity.PeerRole appRole = Windows.Networking.Proximity.PeerRole.Peer;
    bool launchedByTap = false;
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        LaunchActivatedEventArgs launchArgs = e.Parameter as LaunchActivatedEventArgs;
    
        if (launchArgs.Arguments.Contains("Windows.Networking.Proximity.PeerFinder:StreamSocket"))
        {
            launchedByTap = true;
    
            if (launchArgs.Arguments.Contains("Role=Host"))
            {
                appRole = Windows.Networking.Proximity.PeerRole.Host;
            }
            else if (launchArgs.Arguments.Contains("Role=Client"))
            {
                appRole = Windows.Networking.Proximity.PeerRole.Client;
            }
            else
            {
                appRole = Windows.Networking.Proximity.PeerRole.Peer;
            }
        }
    }
    
    bool started = false;
    
    // Click event for "Advertise" button.
    void AdvertiseForPeers(object sender, RoutedEventArgs e)
    {
        if (!started)
        {
            Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
            if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
            {
                Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                    TriggeredConnectionStateChanged;
    
                WriteMessageText("You can tap to connect a peer device that is " +
                                 "also advertising for a connection.\n");
            }
            else
            {
                WriteMessageText("Tap to connect is not supported.\n");
            }
    
            if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                 Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
            {
                WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            }
    
            // Set the peer role selected by the user.  
            if (launchedByTap)
            {
                Windows.Networking.Proximity.PeerFinder.Role = appRole;
            }
            else
            {
                switch (GetRoleFromUser())
                {
                    case "Peer":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Peer;
                        break;
                    case "Host":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Host;
                        break;
                    case "Client":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Client;
                        break;
                }
            }
    
            // Set discoveryData property with user supplied text. 
            var discData = GetDiscoveryDataFromUser();
            var writer = new Windows.Storage.Streams.DataWriter(
                new Windows.Storage.Streams.InMemoryRandomAccessStream());
            writer.WriteString(discData);
            Windows.Networking.Proximity.PeerFinder.DiscoveryData =
                writer.DetachBuffer();
    
            Windows.Networking.Proximity.PeerFinder.Start();
            started = true;
        }
    }
    
    // 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;
            });
    }
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.ApplicationModel.Activation;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace Proximity_PeerWatcher
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class PeerRole : Page
        {
            public PeerRole()
            {
                this.InitializeComponent();
            }
    
            TextBox DisplayNameTextBox = new TextBox();
            TextBlock MessageBlock = new TextBlock();
    
            private void TriggeredConnectionStateChanged(
                object sender,
                Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
            {
                if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
                {
    
                }
                if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
                {
    
                }
            }
    
            private string GetDiscoveryDataFromUser()
            {
                return "";
            }
    
            private string GetRoleFromUser()
            {
                return "Peer";
            }
    
            // <SnippetPeerRole_CS>
            // Default to the peer role.
            Windows.Networking.Proximity.PeerRole appRole = Windows.Networking.Proximity.PeerRole.Peer;
            bool launchedByTap = false;
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                LaunchActivatedEventArgs launchArgs = e.Parameter as LaunchActivatedEventArgs;
    
                if (launchArgs.Arguments.Contains("Windows.Networking.Proximity.PeerFinder:StreamSocket"))
                {
                    launchedByTap = true;
    
                    if (launchArgs.Arguments.Contains("Role=Host"))
                    {
                        appRole = Windows.Networking.Proximity.PeerRole.Host;
                    }
                    else if (launchArgs.Arguments.Contains("Role=Client"))
                    {
                        appRole = Windows.Networking.Proximity.PeerRole.Client;
                    }
                    else
                    {
                        appRole = Windows.Networking.Proximity.PeerRole.Peer;
                    }
                }
            }
    
            bool started = false;
    
            // Click event for "Advertise" button.
            void AdvertiseForPeers(object sender, RoutedEventArgs e)
            {
                if (!started)
                {
                    Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
                    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
                    {
                        Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                            TriggeredConnectionStateChanged;
    
                        WriteMessageText("You can tap to connect a peer device that is " +
                                         "also advertising for a connection.\n");
                    }
                    else
                    {
                        WriteMessageText("Tap to connect is not supported.\n");
                    }
    
                    if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                         Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
                    {
                        WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
                    }
    
                    // Set the peer role selected by the user.  
                    if (launchedByTap)
                    {
                        Windows.Networking.Proximity.PeerFinder.Role = appRole;
                    }
                    else
                    {
                        switch (GetRoleFromUser())
                        {
                            case "Peer":
                                Windows.Networking.Proximity.PeerFinder.Role =
                                    Windows.Networking.Proximity.PeerRole.Peer;
                                break;
                            case "Host":
                                Windows.Networking.Proximity.PeerFinder.Role =
                                    Windows.Networking.Proximity.PeerRole.Host;
                                break;
                            case "Client":
                                Windows.Networking.Proximity.PeerFinder.Role =
                                    Windows.Networking.Proximity.PeerRole.Client;
                                break;
                        }
                    }
    
                    // Set discoveryData property with user supplied text. 
                    var discData = GetDiscoveryDataFromUser();
                    var writer = new Windows.Storage.Streams.DataWriter(
                        new Windows.Storage.Streams.InMemoryRandomAccessStream());
                    writer.WriteString(discData);
                    Windows.Networking.Proximity.PeerFinder.DiscoveryData =
                        writer.DetachBuffer();
    
                    Windows.Networking.Proximity.PeerFinder.Start();
                    started = true;
                }
            }
    
            // 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;
                    });
            }
            // </SnippetPeerRole_CS>
    
        }
    }
    
    // Default to the peer role.
    var appRole = Windows.Networking.Proximity.PeerRole.peer;
    var launchedFromTap = false; 
    
    app.onactivated = function (args) {
        if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            Windows.Networking.Proximity.PeerFinder.addEventListener("connectionrequested", connectionRequested);
    
            // Detect if app launched from a tap.
            if ((args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) &&
                (args.detail.arguments === "Windows.Networking.Proximity.PeerFinder:StreamSocket")) {
    
                launchedFromTap = true; 
    
                if (args.detail.arguments.search("Role=Host") !== -1) { 
                    appRole = Windows.Networking.Proximity.PeerRole.host; 
                } 
                else if (args.detail.arguments.search("Role=Client") !== -1) { 
                    appRole = Windows.Networking.Proximity.PeerRole.client; 
                } 
                else { 
                    appRole = Windows.Networking.Proximity.PeerRole.peer; 
                } 
            } 
        }
    
        advertiseForPeers(true);
    
        args.setPromise(WinJS.UI.processAll());
    }
    
    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
                "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }       
    
        if (!started) {
            // Set the peer role selected by the user.  
            if (launchedByTap) { 
                Windows.Networking.Proximity.PeerFinder.role = appRole; 
            } 
            else { 
                switch (getRoleFromUser()) { 
                    case "peer": 
                        Windows.Networking.Proximity.PeerFinder.role = 
                            Windows.Networking.Proximity.PeerRole.peer; 
                        break; 
                    case "host": 
                        Windows.Networking.Proximity.PeerFinder.role = 
                            Windows.Networking.Proximity.PeerRole.host; 
                        break; 
                    case "client": 
                        Windows.Networking.Proximity.PeerFinder.role = 
                            Windows.Networking.Proximity.PeerRole.client; 
                        break; 
                } 
            } 
    
            // Set discoveryData property with user supplied text. 
            var discData = getDiscoveryDataFromUser();
            var writer = Windows.Storage.Streams.DataWriter(
                new Windows.Storage.Streams.InMemoryRandomAccessStream()); 
            writer.writeString(discData); 
            Windows.Networking.Proximity.PeerFinder.discoveryData = 
                writer.detachBuffer(); 
    
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
  • SupportedDiscoveryTypes
    SupportedDiscoveryTypes
    SupportedDiscoveryTypes
    SupportedDiscoveryTypes

    Gets a value that indicates which discovery options are available to use with the PeerFinder class.

    public static PeerDiscoveryTypes SupportedDiscoveryTypes { get; }public static PeerDiscoveryTypes SupportedDiscoveryTypes { get; }Public Static ReadOnly Property SupportedDiscoveryTypes As PeerDiscoveryTypes

    Property Value

    Remarks

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    

Methods

  • ConnectAsync(Windows.Networking.Proximity.PeerInformation)
    ConnectAsync(Windows.Networking.Proximity.PeerInformation)
    ConnectAsync(Windows.Networking.Proximity.PeerInformation)
    ConnectAsync(Windows.Networking.Proximity.PeerInformation)

    Connects to a peer discovered by a call to the FindAllPeersAsync() method.

    public static IAsyncOperation<StreamSocket> ConnectAsync(Windows.Networking.Proximity.PeerInformation peerInformation)public static IAsyncOperation<StreamSocket> ConnectAsync(Windows.Networking.Proximity.PeerInformation peerInformation)Public Static Function ConnectAsync(peerInformation As Windows.Networking.Proximity.PeerInformation) As IAsyncOperation( Of StreamSocket )

    Parameters

    Returns

    • An asynchronous operation for connecting to a remote peer using the supplied @Windows.Networking.Sockets.StreamSocket.#ctor object.

    Remarks

    You can obtain an instance of a PeerInformation object for a peer from a call to the FindAllPeersAsync() method, or in a handler for the ConnectionRequested event.

    If an app calls the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method to create a connection with a peer, the app will no longer advertise for a connection and will not be found by the FindAllPeersAsync() method until the app calls the Close() method to close the socket connection.

    If you open a socket connection by calling the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method, only one socket connection can be open at a time for the computer. If your app, or another app calls the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method, then the existing socket connection will close.

    An Access Denied exception will be thrown if you attempt to call ConnectAsync when your app is in the background.

    Important

    The Proximity APIs do not provide authentication. You should avoid exchanging sensitive data with these APIs.

    Windows Phone 8

    Wi-Fi Direct is not supported on Windows Phone 8. For more information, see Proximity.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    
  • CreateWatcher()
    CreateWatcher()
    CreateWatcher()
    CreateWatcher()

    Creates a new instance of a PeerWatcher object for dynamic discovery of peer apps.

    public static PeerWatcher CreateWatcher()public static PeerWatcher CreateWatcher()Public Static Function CreateWatcher() As PeerWatcher

    Returns

    Remarks

    You must first call the Start(System.String) method before calling the CreateWatcher() method.

    If you call the CreateWatcher() method multiple times, you will receive a reference to the same PeerWatcher instance.

    private PeerWatcher _peerWatcher;
    private bool _peerWatcherIsRunning = false;
    private bool _peerFinderStarted = false;
    
    // The list of peers discovered by the PeerWatcher.
    ObservableCollection<PeerInformation> _discoveredPeers = new ObservableCollection<PeerInformation>();
    void PeerFinder_StartPeerWatcher(object sender, RoutedEventArgs e)
    {
        if (!_peerFinderStarted)
        {
            // PeerFinder must be started first.
            return;
        }
    
        if (_peerWatcherIsRunning)
        {
            // PeerWatcher is already running.
            return;
        }
    
        try
        {
            if (_peerWatcher == null)
            {
                _peerWatcher = PeerFinder.CreateWatcher();
    
                // Add PeerWatcher event handlers. Only add handlers once.
                _peerWatcher.Added += PeerWatcher_Added;
                _peerWatcher.Removed += PeerWatcher_Removed;
                _peerWatcher.Updated += PeerWatcher_Updated;
                _peerWatcher.EnumerationCompleted += PeerWatcher_EnumerationCompleted;
                _peerWatcher.Stopped += PeerWatcher_Stopped;
            }
    
            // Empty the list of discovered peers.
            _discoveredPeers.Clear();
    
            // Start the PeerWatcher.
            _peerWatcher.Start();
    
            _peerWatcherIsRunning = true;
        }
        catch (Exception ex)
        {
            // Exceptions can occur if PeerWatcher.Start is called multiple times or
            // PeerWatcher.Start is called the PeerWatcher is stopping.
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_peerWatcher != null)
        {
            // Remove event handlers.
            _peerWatcher.Added -= PeerWatcher_Added;
            _peerWatcher.Removed -= PeerWatcher_Removed;
            _peerWatcher.Updated -= PeerWatcher_Updated;
            _peerWatcher.EnumerationCompleted -= PeerWatcher_EnumerationCompleted;
            _peerWatcher.Stopped -= PeerWatcher_Stopped;
    
            _peerWatcher = null;
        }
    }
    
    // For an introduction to the Blank template, see the following documentation:
    // http://go.microsoft.com/fwlink/?LinkId=232509
    (function () {
        "use strict";
    
        var app = WinJS.Application;
        var activation = Windows.ApplicationModel.Activation;
    
        app.onactivated = function (args) {
            if (args.detail.kind === activation.ActivationKind.launch) {
                if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize
                    // your application here.
                } else {
                    // TODO: This application has been reactivated from suspension.
                    // Restore application state here.
                }
                args.setPromise(WinJS.UI.processAll());
            }
        };
    
        app.oncheckpoint = function (args) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // args.setPromise().
        };
    
    
        // <Snippet_StartPeerWatcher_JS>
        var _peerWatcher;
        var _peerWatcherIsRunning = false;
        var _peerFinderStarted = false;
    
        // The list of peers discovered by the PeerWatcher.
        var _discoveredPeers = new Array();
    
        function peerFinder_StartPeerWatcher() {
            if (!_peerFinderStarted) {
                // PeerFinder must be started first.
               return;
            }
    
            if (_peerWatcherIsRunning) {
                // PeerWatcher is already running.
                return;
            }
    
            try {
                if (!_peerWatcher)
                {
                    _peerWatcher = PeerFinder.createWatcher();
    
                    // Add PeerWatcher event handlers. Only add handlers once.
                    peerWatcher.addEventListener("added", peerWatcher_Added); 
                    peerWatcher.addEventListener("removed", peerWatcher_Removed); 
                    peerWatcher.addEventListener("updated",  peerWatcher_Updated); 
                    peerWatcher.addEventListener("enumerationcompleted", peerWatcher_EnumerationCompleted); 
                    peerWatcher.addEventListener("stopped", peerWatcher_Stopped); 
                }
    
                // Empty the list of discovered peers.
                _discoveredPeers = new Array();
    
                // Start the PeerWatcher.
                _peerWatcher.start();
    
                _peerWatcherIsRunning = true;
            }
            catch (ex)
            {
                // Exceptions can occur if PeerWatcher.Start is called multiple times or
                // PeerWatcher.Start is called the PeerWatcher is stopping.
            }
        }
            
        function cleanup() {
            if (_peerWatcher) {
                // Remove event handlers.
                peerWatcher.removeEventListener("added", peerWatcher_Added); 
                peerWatcher.removeEventListener("removed", peerWatcher_Removed); 
                peerWatcher.removeEventListener("updated", peerWatcher_Updated); 
                peerWatcher.removeEventListener("enumerationCompleted", peerWatcher_EnumerationCompleted); 
                peerWatcher.removeEventListener("stopped", peerWatcher_Stopped); 
    
                _peerWatcher = null;
            }
        }
        // </Snippet_StartPeerWatcher_JS>
    
        // <Snippet_StopPeerWatcher_JS>
        function peerFinder_StopPeerWatcher() {
            try {
                _peerWatcher.Stop();
            }
            catch (ex) {
                // Handle the exception.
            }
        }
        // </Snippet_StopPeerWatcher_JS>
    
        // <Snippet_PeerWatcherAdded_JS>
        function peerWatcher_Added(peerInfo) {
            _discoveredPeers.Add(peerInfo);
        }
        // </Snippet_PeerWatcherAdded_JS>
    
        // <Snippet_PeerWatcherRemoved_JS>
        function peerWatcher_Removed(peerInfo)
        {
            // Find and remove the peer form the list of discovered peers.
            var match = null;
            var i;
            _discoveredPeers.forEach(function (e, i) { 
                if (e.id === peerInfo.id) { match = e; index = i; } 
            }); 
            if (match) { 
                _discoveredPeers.splice(index, 1); 
            } 
        }
        // </Snippet_PeerWatcherRemoved_JS>
    
        // <Snippet_PeerWatcherUpdated_JS>
        function peerWatcher_Updated(peerInfo)
        {
            // Find and update the peer in the list of discovered peers.
            var match = null;
            var i;
            _discoveredPeers.forEach(function (e, i) { 
                if (e.id === peerInfo.id) { match = e; index = i; } 
            }); 
            if (match) { 
                _discoveredPeers.setAt(index, peerInfo); 
            } 
        }
        // </Snippet_PeerWatcherUpdated_JS>
    
        // <Snippet_PeerWatcherEnumerationCompleted_JS>
        function peerWatcher_EnumerationCompleted()
        {
            if (_discoveredPeers.length == 0)
            {
                // No peers discovered for this enumeration.
            }
        }
        // </Snippet_PeerWatcherEnumerationCompleted_JS>
    
        // <Snippet_PeerWatcherStopped_JS>
        function peerWatcher_Stopped()
        {
            _peerWatcherIsRunning = false;
    
            // Update UI now that the PeerWatcher is stopped.
        }
        // </Snippet_PeerWatcherStopped_JS>
    
    
        app.start();
    })();
    
    var _peerWatcher;
    var _peerWatcherIsRunning = false;
    var _peerFinderStarted = false;
    
    // The list of peers discovered by the PeerWatcher.
    var _discoveredPeers = new Array();
    
    function peerFinder_StartPeerWatcher() {
        if (!_peerFinderStarted) {
            // PeerFinder must be started first.
           return;
        }
    
        if (_peerWatcherIsRunning) {
            // PeerWatcher is already running.
            return;
        }
    
        try {
            if (!_peerWatcher)
            {
                _peerWatcher = PeerFinder.createWatcher();
    
                // Add PeerWatcher event handlers. Only add handlers once.
                peerWatcher.addEventListener("added", peerWatcher_Added); 
                peerWatcher.addEventListener("removed", peerWatcher_Removed); 
                peerWatcher.addEventListener("updated",  peerWatcher_Updated); 
                peerWatcher.addEventListener("enumerationcompleted", peerWatcher_EnumerationCompleted); 
                peerWatcher.addEventListener("stopped", peerWatcher_Stopped); 
            }
    
            // Empty the list of discovered peers.
            _discoveredPeers = new Array();
    
            // Start the PeerWatcher.
            _peerWatcher.start();
    
            _peerWatcherIsRunning = true;
        }
        catch (ex)
        {
            // Exceptions can occur if PeerWatcher.Start is called multiple times or
            // PeerWatcher.Start is called the PeerWatcher is stopping.
        }
    }
        
    function cleanup() {
        if (_peerWatcher) {
            // Remove event handlers.
            peerWatcher.removeEventListener("added", peerWatcher_Added); 
            peerWatcher.removeEventListener("removed", peerWatcher_Removed); 
            peerWatcher.removeEventListener("updated", peerWatcher_Updated); 
            peerWatcher.removeEventListener("enumerationCompleted", peerWatcher_EnumerationCompleted); 
            peerWatcher.removeEventListener("stopped", peerWatcher_Stopped); 
    
            _peerWatcher = null;
        }
    }
    
  • FindAllPeersAsync()
    FindAllPeersAsync()
    FindAllPeersAsync()
    FindAllPeersAsync()

    Asynchronously browses for peer devices that are running the same app within wireless range.

    public static IAsyncOperation<PeerInformation>> FindAllPeersAsync()public static IAsyncOperation<PeerInformation>> FindAllPeersAsync()Public Static Function FindAllPeersAsync() As IAsyncOperation( Of PeerInformation )

    Returns

    • The asynchronous operation for browsing for peer devices that are running your app.

    Remarks

    If your app is running on a PC, you can browse for peer PCs that are running your app. Peer discovery in this case takes place over Wi-Fi Direct. If your app is running on a phone, you can browse for peer phones that are running your app. In this case, peer discovery takes place over Bluetooth. Because the transport used for peer discovery differs between PC and phone, your app running on a PC can only find peer PCs and your app running on a phone can only find peer phones.

    When the asynchronous browsing operation finishes successfully, it returns a list of peers that are within wireless range. A peer is a device that has an app running in the foreground with a matching app Id. A peer can also have a matching browse Id that's specified as an alternate identity. For more information, see AlternateIdentities.

    If an app calls the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method to create a connection with a peer, the app will no longer advertise for a connection and will not be found by the FindAllPeersAsync() method until the app calls the Close() method to close the socket connection.

    You will only find peers where the device is within wireless range and the peer app is running in the foreground. If a peer app is running in the background, proximity does not advertise for peer connections.

    As an alternative to the FindAllPeersAsync() method, you can dynamically search for peer apps as they are discovered within range using the PeerWatcher object.

    Windows Phone 8

    Wi-Fi Direct is not supported on Windows Phone 8. For more information, see Proximity.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    
  • Start()
    Start()
    Start()
    Start()

    Makes an app discoverable to remote peers.

    public static void Start()public static void Start()Public Static Function Start() As void

    Remarks

    You can call the Start method to begin the process of finding a peer app and to make your app discoverable to remote peers that call the FindAllPeersAsync() method. A peer is a device that has an app running in the foreground with a matching AppId. A peer can also have a matching Browse Id that's specified as an alternate identity. For more information, see AlternateIdentities.

    You can connect to only one peer at a time if your app is in the peer or client role. If your app is in the host role, you can connect up to 5 clients at a time.

    When an app is activated by tapping a nearby device, the activation parameters indicate whether the PeerFinder should be started or if the app was launched with activation arguments. The format of the activation parameters is "Windows.Networking.Proximity.PeerFinder:StreamSocket Role=<Host|Client>". For more information, see the "Activating apps using Proximity" section of Supporting Proximity and Tapping.

    Important

    Always set the DisplayName property to a unique value for your app before you call the Start(System.String) method.

    Windows Phone 8

    Wi-Fi Direct is not supported on Windows Phone 8. For more information, see Proximity.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    
  • Start(System.String)
    Start(System.String)
    Start(System.String)
    Start(System.String)

    Makes an app discoverable to remote peers.

    public static void Start(System.String peerMessage)public static void Start(System.String peerMessage)Public Static Function Start(peerMessage As System.String) As void

    Parameters

    • peerMessage
      System.String
      System.String
      System.String
      System.String

      The message to deliver to the proximate device.

    Remarks

    You can call the Start method to begin the process of finding a peer app and to make your app discoverable to remote peers that call the FindAllPeersAsync() method. A peer is a device that has an app running in the foreground with a matching AppId. A peer can also have a matching Browse Id that's specified as an alternate identity. For more information, see AlternateIdentities.

    You can use this overload of the Start(System.String) method to send a message to a peer app that will be passed as an app activation argument.

    You can connect to only one peer at a time if your app is in the peer or client role. If your app is in the host role, you can connect up to 5 clients at a time.

    When an app is activated by tapping a nearby device, the activation parameters indicate whether the PeerFinder should be started or if the app was launched with activation arguments. The format of the activation parameters is "Windows.Networking.Proximity.PeerFinder:StreamSocket Role=<Host|Client>". For more information, see the "Activating apps using Proximity" section of Supporting Proximity and Tapping.

    Important

    Always set the DisplayName property to a unique value for your app before you call the Start(System.String) method.

    Windows Phone 8

    Wi-Fi Direct is not supported on Windows Phone 8. For more information, see Proximity.

  • Stop()
    Stop()
    Stop()
    Stop()

    Stops advertising for a peer connection.

    public static void Stop()public static void Stop()Public Static Function Stop() As void

    Remarks

    You can call the Stop() method to stop the PeerFinder when you no longer want to advertise for or accept new triggered (tapped) or browsed connections. Stop() does not close an existing connection. However, the Stop() method will cancel outstanding calls to the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method and triggered connection requests. The Stop() method does not wait for the cancellation to complete.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    

Events

  • ConnectionRequested
    ConnectionRequested
    ConnectionRequested
    ConnectionRequested

    Occurs when a remote peer requests a connection using the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method.

    public static event TypedEventHandler ConnectionRequestedpublic static event TypedEventHandler ConnectionRequestedPublic Static Event ConnectionRequested

    Remarks

    The ConnectionRequested event occurs when a remote peer calls the FindAllPeersAsync() method, finds the current peer, and passes that peer information to the ConnectAsync(Windows.Networking.Proximity.PeerInformation) method to request a connection.

    Important

    The Proximity APIs do not provide authentication. You should avoid exchanging sensitive data with these APIs.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    
  • TriggeredConnectionStateChanged
    TriggeredConnectionStateChanged
    TriggeredConnectionStateChanged
    TriggeredConnectionStateChanged

    Occurs during a tap gesture from a remote peer.

    public static event TypedEventHandler TriggeredConnectionStateChangedpublic static event TypedEventHandler TriggeredConnectionStateChangedPublic Static Event TriggeredConnectionStateChanged

    Remarks

    You can determine when a peer is available to connect to, and the progress of a connection to a peer, by using the TriggeredConnectionStateChanged event. Use the TriggeredConnectionStateChanged event to determine when a new peer has been found and to access the connection to that peer after you've finished connecting.

    The TriggeredConnectionStateChanged event occurs several times during a tap gesture. You can determine where you are in the connection process by using the State property.

    The first State value in a Proximity connection is PeerFound. At this point, you can tell users of your app that the Proximity gesture is complete and they can pull their devices away.

    If the State property returns Connecting, you know that your device initiated the tap gesture. If the State property returns Listening, you know that the other device initiated the tap gesture. This information is useful in determining which peer should initiate communications when the connection is complete.

    When the State property returns Completed, you can access the Socket property to obtain a reference to a @Windows.Networking.Sockets.StreamSocket.#ctor object. You can use this reference to communicate with the peer app. The transport over which this communication takes place on this socket connection will either be Bluetooth, Infrastructure or Wi-Fi Direct.

    Wi-Fi Direct is not supported for Windows Phone Store app.

    Examples

    var started = false;
    
    // Click event for "Advertise" button.
    function advertiseForPeers(launchedFromTap) {
        Windows.Networking.Proximity.PeerFinder.displayName = displayNameTextBox.Text;
    
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.triggered) {
    
            Windows.Networking.Proximity.PeerFinder.addEventListener(
                "triggeredconnectionstatechanged", triggeredConnectionStateChanged);
    
            id("messageDiv").innerHTML +=
                "You can tap to connect a peer device that is " +
                "also advertising for a connection.<br />";
        } else {
            id("messageDiv").innerHTML +=
          "Tap to connect is not supported.<br />";
        }
    
        if (!launchedFromTap) {
            if (!(Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                  Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)) {
                id("messageDiv").innerHTML +=
                    "Peer discovery using Wi-Fi Direct is not supported.<br />";
            }
        }
    
        if (!started) {
            Windows.Networking.Proximity.PeerFinder.start();
            started = true;
        }
    }
    
    function triggeredConnectionStateChanged(e) {
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.peerFound) {
            id("messageDiv").innerHTML +=
                "Peer found. You may now pull your devices out of proximity.<br />";
        }
        if (e.state === Windows.Networking.Proximity.TriggeredConnectState.completed) {
            id("messageDiv").innerHTML += "Connected. You may now send a message.<br />";
            sendMessage(e.socket);
        }
    }
    
    
    // Click event for "Browse" button.
    function findPeers() {
        if (Windows.Networking.Proximity.PeerFinder.supportedDiscoveryTypes &
            Windows.Networking.Proximity.PeerDiscoveryTypes.browse) {
    
            Windows.Networking.Proximity.PeerFinder.findAllPeersAsync().done(
        function (peerInfoCollection) {
            if (peerInfoCollection.length > 0) {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                connectToPeer(peerInfoCollection[0]);
            }
        },
        function (err) {
            id("messageDiv").innerHTML += "Error finding peers: " + err + "<br />";
        });
        } else {
            id("messageDiv").innerHTML +=
      "Peer discovery using Wi-Fi Direct is not supported.<br />";
        }
    }
    
    function connectToPeer(peerInfo) {
        id("messageDiv").innerHTML += ("Peer found. Connecting to " + peerInfo.displayName + "<br />");
        Windows.Networking.Proximity.PeerFinder.connectAsync(peerInfo).done(
            function (socket) {
                id("messageDiv").innerHTML += "Connection successful. You may now send messages.<br />";
                sendMessage(socket);
            },
            function (err) {
                id("messageDiv").innerHTML += "Connection failed: " + err + "<br />";
            });
    
        requestingPeer = null;
    }
    
    function stopFindingPeers() {
        Windows.Networking.Proximity.PeerFinder.stop();
        started = false;
        if (proximitySocket != null) { closeSocket(); }
    }
    
    // Handle external connection requests.
    var requestingPeer;
    
    function connectionRequested(e) {
        id("messageDiv").innerHTML +=
            "Connection requested by " + e.peerInformation.DisplayName + ". " +
            "Click 'Accept Connection' to connect.";
        requestingPeer = e.PeerInformation;
    }
    
    function acceptConnection() {
        if (requestingPeer == null) {
            id("messageDiv").innerHTML += "No peer connection has been requested.";
            return;
        }
    
        connectToPeer(requestingPeer);
    }
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName;
        Windows.Networking.Proximity.PeerFinder.ConnectionRequested += ConnectionRequested;
    
        // If activated from launch or from the background, create a peer connection.
        var args = e.Parameter as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
        if (args != null && args.Kind == Windows.ApplicationModel.Activation.ActivationKind.Launch)
        {
            if (args.Arguments == "Windows.Networking.Proximity.PeerFinder:StreamSocket")
            {
                AdvertiseForPeersButton_Click(null, null);
            }
        }
    }
    
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        if (_started)
        {
            // Detach the callback handler (there can only be one PeerConnectProgress handler).
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
            // Detach the incoming connection request event handler.
            Windows.Networking.Proximity.PeerFinder.ConnectionRequested -= ConnectionRequested;
            Windows.Networking.Proximity.PeerFinder.Stop();
            CloseSocket();
            _started = false;
        }
    }
    
    // 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;
            });
    }
    
    bool _started = false;
    
    // Click event handler for "Advertise" button.
    private void AdvertiseForPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if (_started) 
        {
            WriteMessageText("You are already advertising for a connection.\n");
            return; 
        }
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
        {
            Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                TriggeredConnectionStateChanged;
    
            WriteMessageText("You can tap to connect a peer device that is " +
                             "also advertising for a connection.\n");
        }
        else
        {
            WriteMessageText("Tap to connect is not supported.\n");
        }
    
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
        }
    
       Windows.Networking.Proximity.PeerFinder.Start();
       _started = true;
    }
    
    private void TriggeredConnectionStateChanged(
        object sender,
        Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs e)
    {
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.PeerFound)
        {
            WriteMessageText("Peer found. You may now pull your devices out of proximity.\n");
        }
        if (e.State == Windows.Networking.Proximity.TriggeredConnectState.Completed)
        {
            WriteMessageText("Connected. You may now send a message.\n");
            SendMessage(e.Socket);
        }
    }
    
    // Click event handler for "Browse" button.
    async private void FindPeersButton_Click(object sender, RoutedEventArgs e)
    {
        if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
             Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
        {
            WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
            return;
        }
    
        try
        {
            var peerInfoCollection = await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync();
            if (peerInfoCollection.Count > 0)
            {
                // Connect to first peer found - example only.
                // In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection[0]);
            }
        }
        catch (Exception err)
        {
            WriteMessageText("Error finding peers: " + err.Message + "\n");
        }
    }
    
    async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
    {
        WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
        try
        {
            Windows.Networking.Sockets.StreamSocket socket =
                await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);
    
            WriteMessageText("Connection successful. You may now send messages.\n");
            SendMessage(socket);
        }
        catch (Exception err)
        {
            WriteMessageText("Connection failed: " + err.Message + "\n");
        }
    
        requestingPeer = null;
    }
    
    // Click event handler for "Stop" button.
    private void StopFindingPeersButton_Click(object sender, RoutedEventArgs e)
    {
        _started = false;
        Windows.Networking.Proximity.PeerFinder.Stop();
        if (proximitySocket != null) { CloseSocket(); }
    }
    
    // Handle external connection requests.
    Windows.Networking.Proximity.PeerInformation requestingPeer;
    
    private void ConnectionRequested(object sender,
        Windows.Networking.Proximity.ConnectionRequestedEventArgs e)
    {
        requestingPeer = e.PeerInformation;
        WriteMessageText("Connection requested by " + requestingPeer.DisplayName + ". " +
            "Click 'Accept Connection' to connect.");
    }
    
    private void AcceptConnectionButton_Click(object sender, RoutedEventArgs e)
    {
        if (requestingPeer == null)
        {
            WriteMessageText("No peer connection has been requested.");
            return;
        }
    
        ConnectToPeer(requestingPeer);
    }
    
    Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)
        DisplayNameTextBox.Text = Windows.Networking.Proximity.PeerFinder.DisplayName
        AddHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
    
        ' If activated from launch or from the background, create a peer connection.
        Dim args = TryCast(e.Parameter, Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
        If args IsNot Nothing AndAlso args.Kind = Windows.ApplicationModel.Activation.ActivationKind.Launch Then
    
            If args.Arguments = "Windows.Networking.Proximity.PeerFinder:StreamSocket" Then
                AdvertiseForPeersButton_Click()
            End If
        End If
    End Sub
    
    Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
        If _started Then
            ' Detach the callback handler (there can only be one PeerConnectProgress handler).
            RemoveHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged, AddressOf TriggeredConnectionStateChanged
            ' Detach the incoming connection request event handler.
            RemoveHandler Windows.Networking.Proximity.PeerFinder.ConnectionRequested, AddressOf ConnectionRequested
            Windows.Networking.Proximity.PeerFinder.Stop()
            CloseSocket()
            _started = False
        End If
    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
    
    Private _started As Boolean = False
    
    ' Click event handler for "Advertise" button.
    Private Sub AdvertiseForPeersButton_Click()
    
        If _started Then
            WriteMessageText("You are already advertising for a connection." & vbCrLf)
            Return
        End If
    
        Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text
    
        If ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) =
             Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) Then
    
            AddHandler Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged,
                AddressOf TriggeredConnectionStateChanged
    
            WriteMessageText("You can tap to connect a peer device that is " &
                             "also advertising for a connection." & vbCrLf)
        Else
            WriteMessageText("Tap to connect is not supported." & vbCrLf)
        End If
    
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
        End If
    
        Windows.Networking.Proximity.PeerFinder.Start()
        _started = True
    End Sub
    
    Private Sub TriggeredConnectionStateChanged(
        sender As Object,
        e As Windows.Networking.Proximity.TriggeredConnectionStateChangedEventArgs)
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.PeerFound Then
    
            WriteMessageText("Peer found. You may now pull your devices out of proximity." & vbCrLf)
        End If
    
        If e.State = Windows.Networking.Proximity.TriggeredConnectState.Completed Then
            WriteMessageText("Connected. You may now send a message." & vbCrLf)
            SendMessage(e.Socket)
        End If
    End Sub
    
    ' Click event handler for "Browse" button.
    Private Async Sub FindPeersButton_Click()
        If (Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes And
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) <>
            Windows.Networking.Proximity.PeerDiscoveryTypes.Browse Then
    
            WriteMessageText("Peer discovery using Wifi-Direct is not supported." & vbCrLf)
            Return
        End If
    
        Try
            Dim peerInfoCollection = Await Windows.Networking.Proximity.PeerFinder.FindAllPeersAsync()
            If peerInfoCollection.Count > 0 Then
                ' Connect to first peer found - example only.
                ' In your app, provide the user with a list of available peers.
                ConnectToPeer(peerInfoCollection(0))
            End If
        Catch err As Exception
            WriteMessageText("Error finding peers: " & err.Message & vbCrLf)
        End Try
    End Sub
    
    Private Async Sub ConnectToPeer(peerInfo As Windows.Networking.Proximity.PeerInformation)
    
        WriteMessageText("Peer found. Connecting to " & peerInfo.DisplayName & vbCrLf)
        Try
            Dim socket = Await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo)
    
            WriteMessageText("Connection successful. You may now send messages." & vbCrLf)
            SendMessage(socket)
        Catch err As Exception
            WriteMessageText("Connection failed: " & err.Message & vbCrLf)
        End Try
    
        requestingPeer = Nothing
    End Sub
    
    ' Click event handler for "Stop" button.
    Private Sub StopFindingPeersButton_Click()
    
        _started = False
        Windows.Networking.Proximity.PeerFinder.Stop()
        If proximitySocket IsNot Nothing Then CloseSocket()
    End Sub
    
    ' Handle external connection requests.
    Private requestingPeer As Windows.Networking.Proximity.PeerInformation
    
    Private Sub ConnectionRequested(sender As Object,
        e As Windows.Networking.Proximity.ConnectionRequestedEventArgs)
    
        requestingPeer = e.PeerInformation
    
        WriteMessageText("Connection requested by " & requestingPeer.DisplayName & ". " &
            "Click 'Accept Connection' to connect.")
    End Sub
    
    Private Sub AcceptConnectionButton_Click()
        If requestingPeer Is Nothing Then
            WriteMessageText("No peer connection has been requested.")
            Return
        End If
    
        ConnectToPeer(requestingPeer)
    End Sub
    

Capabilities

proximity
ID_CAP_PROXIMITY [Windows Phone]
ID_CAP_NETWORKING [Windows Phone] ID_CAP_NETWORKING [Windows Phone]

Attributes

Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute

Details

Assembly

Windows.Networking.Proximity.dll