다음을 통해 공유


PeerFinder.Start 메서드

정의

오버로드

Start()

원격 피어에서 앱을 검색할 수 있도록 합니다.

Start(String)

원격 피어에서 앱을 검색할 수 있도록 합니다.

Start()

원격 피어에서 앱을 검색할 수 있도록 합니다.

public:
 static void Start();
/// [Windows.Foundation.Metadata.Overload("Start")]
 static void Start();
[Windows.Foundation.Metadata.Overload("Start")]
public static void Start();
function start()
Public Shared Sub Start ()
특성

Windows 요구 사항

앱 기능
ID_CAP_NETWORKING [Windows Phone] ID_CAP_NETWORKING [Windows Phone] ID_CAP_PROXIMITY [Windows Phone] proximity ID_CAP_PROXIMITY [Windows Phone]

예제

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 메서드를 호출하여 피어 앱을 찾는 프로세스를 시작하고 FindAllPeersAsync 메서드를 호출하는 원격 피어에서 앱을 검색할 수 있도록 할 수 있습니다. 피어는 일치하는 AppId를 사용하여 포그라운드에서 실행되는 앱이 있는 디바이스입니다. 피어는 대체 ID로 지정된 일치하는 찾아보기 ID를 가질 수도 있습니다. 자세한 내용은 AlternateIdentities를 참조하세요.

앱이 피어 또는 클라이언트 역할에 있는 경우 한 번에 하나의 피어에만 연결할 수 있습니다. 앱이 호스트 역할에 있는 경우 한 번에 최대 5개의 클라이언트를 연결할 수 있습니다.

근처 디바이스를 탭하여 앱을 활성화하면 활성화 매개 변수는 PeerFinder 를 시작해야 하는지 또는 활성화 인수를 사용하여 앱을 시작했는지 여부를 나타냅니다. 활성화 매개 변수의 형식은 "Windows.Networking.Proximity.PeerFinder:StreamSocket Role=<Host|클라이언트>"입니다. 자세한 내용은 근접 지원 및 탭의 "근접을 사용하여 앱 활성화" 섹션 을 참조하세요.

중요

Start 메서드를 호출하기 전에 항상 DisplayName 속성을 앱의 고유한 값으로 설정합니다.

Windows Phone 8

Wi-Fi Direct는 Windows Phone 8에서 지원되지 않습니다.

추가 정보

적용 대상

Start(String)

원격 피어에서 앱을 검색할 수 있도록 합니다.

public:
 static void Start(Platform::String ^ peerMessage);
/// [Windows.Foundation.Metadata.Overload("StartWithMessage")]
 static void Start(winrt::hstring const& peerMessage);
[Windows.Foundation.Metadata.Overload("StartWithMessage")]
public static void Start(string peerMessage);
function start(peerMessage)
Public Shared Sub Start (peerMessage As String)

매개 변수

peerMessage
String

Platform::String

winrt::hstring

근접 디바이스에 전달할 메시지입니다.

특성

Windows 요구 사항

앱 기능
ID_CAP_NETWORKING [Windows Phone] proximity ID_CAP_PROXIMITY [Windows Phone]

설명

Start 메서드를 호출하여 피어 앱을 찾는 프로세스를 시작하고 FindAllPeersAsync 메서드를 호출하는 원격 피어에서 앱을 검색할 수 있도록 할 수 있습니다. 피어는 일치하는 AppId를 사용하여 포그라운드에서 실행되는 앱이 있는 디바이스입니다. 피어는 대체 ID로 지정된 일치하는 찾아보기 ID를 가질 수도 있습니다. 자세한 내용은 AlternateIdentities를 참조하세요.

Start 메서드의 이 오버로드를 사용하여 앱 활성화 인수로 전달될 피어 앱에 메시지를 보낼 수 있습니다.

앱이 피어 또는 클라이언트 역할에 있는 경우 한 번에 하나의 피어에만 연결할 수 있습니다. 앱이 호스트 역할에 있는 경우 한 번에 최대 5개의 클라이언트를 연결할 수 있습니다.

근처 디바이스를 탭하여 앱을 활성화하면 활성화 매개 변수는 PeerFinder 를 시작해야 하는지 또는 활성화 인수를 사용하여 앱을 시작했는지 여부를 나타냅니다. 활성화 매개 변수의 형식은 "Windows.Networking.Proximity.PeerFinder:StreamSocket Role=<Host|클라이언트>"입니다. 자세한 내용은 근접 지원 및 탭의 "근접을 사용하여 앱 활성화" 섹션 을 참조하세요.

중요

Start 메서드를 호출하기 전에 항상 DisplayName 속성을 앱의 고유한 값으로 설정합니다.

Windows Phone 8

Wi-Fi Direct는 Windows Phone 8에서 지원되지 않습니다.

추가 정보

적용 대상