private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_publisher == null)
                {
                    _publisher = new WiFiDirectAdvertisementPublisher();
                }

                if (chkListener.IsChecked == true)
                {
                    if (_listener == null)
                    {
                        _listener = new WiFiDirectConnectionListener();
                    }

                    _listener.ConnectionRequested += OnConnectionRequested;
                }

                _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = (chkPreferGroupOwnerMode.IsChecked == true);

                if (cmbListenState.SelectionBoxItem.ToString().Equals("Normal") == true)
                {
                    _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
                }
                else if (cmbListenState.SelectionBoxItem.ToString().Equals("Intensive") == true)
                {
                    _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Intensive;
                }
                else if (cmbListenState.SelectionBoxItem.ToString().Equals("None") == true)
                {
                    _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.None;
                }

                _publisher.StatusChanged += OnStatusChanged;

                _publisher.Start();

                rootPage.NotifyUser("Advertisement started, waiting for StatusChanged callback...", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Error starting Advertisement: " + ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Пример #2
0
 private void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
 {
     //WiFiDirectConnectionRequest connectionRequest = args.GetConnectionRequest();
     //string deviceName = connectionRequest.DeviceInformation.Name;
     //string result = string.Empty;
     //GetData(connectionRequest);
 }
Пример #3
0
        private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new WiFiDirectAdvertisementPublisher();
            _publisher.StatusChanged += OnStatusChanged;

            _listener = new WiFiDirectConnectionListener();

            try
            {
                // This can raise an exception if the machine does not support WiFi. Sorry.
                _listener.ConnectionRequested += OnConnectionRequested;
            }
            catch (Exception ex)
            {
                //rootPage.NotifyUser($"Error preparing Advertisement: {ex}", NotifyType.ErrorMessage);
                return;
            }

            _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;

            _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = false;

            //// Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
            //if (_publisher.Advertisement.IsAutonomousGroupOwnerEnabled && chkLegacySetting.IsChecked.Value)
            //{
            //    _publisher.Advertisement.LegacySettings.IsEnabled = true;
            //    if (!string.IsNullOrEmpty(txtPassphrase.Text))
            //    {
            //        Windows.Security.Credentials.PasswordCredential creds = new Windows.Security.Credentials.PasswordCredential
            //        {
            //            Password = txtPassphrase.Text
            //        };
            //        _publisher.Advertisement.LegacySettings.Passphrase = creds;
            //    }

            //    if (!string.IsNullOrEmpty(txtSsid.Text))
            //    {
            //        _publisher.Advertisement.LegacySettings.Ssid = txtSsid.Text;
            //    }
            //}

            // Add the information elements.
            foreach (WiFiDirectInformationElement informationElement in _informationElements)
            {
                _publisher.Advertisement.InformationElements.Add(informationElement);
            }

            _publisher.Start();

            if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
            {
                //btnStartAdvertisement.IsEnabled = false;
                btnStopAdvertisement.IsEnabled = true;
                //rootPage.NotifyUser("Advertisement started.", NotifyType.StatusMessage);
            }
            else
            {
                // rootPage.NotifyUser($"Advertisement failed to start. Status is {_publisher.Status}", NotifyType.ErrorMessage);
            }
        }
Пример #4
0
        // Initialize advertizing and if Receiver handle connetion request
        public void Init(bool IsReceiver)
        {
            // Create an instance of Wifi Direct advertiser
            if (publisher == null)
            {
                publisher = new WiFiDirectAdvertisementPublisher();
            }

            // Listen to connection request if receiver
            if (IsReceiver)
            {
                WiFiDirectConnectionListener listener = new WiFiDirectConnectionListener();
                listener.ConnectionRequested += (WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs) =>
                {
                    // Because HandleConnectionRequestAsync generates a connection dialog window It request UI Thread
                    WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        // Request a connection to given device
                        var id = connectionRequest.DeviceInformation.Id;
                        //connectionRequest.Dispose();
                        await WifiDirectHandler.ConnectAsync(id, IsReceiver);
                    });
                };
            }
            // Start advertisement with Intensive parameter so that WifiDirect stay enabled even if app is in background
            publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Intensive;
            publisher.Start();
        }
 private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
 {
     WiFiDirectConnectionRequest ConnectionRequest = args.GetConnectionRequest();
     WiFiDirectDevice wfdDevice = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);
     EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
     _ConnectionEstablishState = ConnectionEstablishState.Succeeded;
     OnConnectionEstalblishResult?.Invoke(this, _ConnectionEstablishState);
 }
Пример #6
0
 private static void DisposeWiFiPublisher()
 {
     wifiPublisher.Stop();
     wifiPublisher.StatusChanged -= WifiPublisher_StatusChanged;
     wifiPublisher = null;
     wifiConnectionListener.ConnectionRequested -= WifiConnectionListener_ConnectionRequested;
     wifiConnectionListener = null;
 }
Пример #7
0
 private void StartListener()
 {
     // Create WiFiDirectConnectionListener
     _connectionListener = new WiFiDirectConnectionListener();
     _connectionListener.ConnectionRequested += OnConnectionRequested;
     if (_listener != null)
     {
         _listener.LogMessage("Connection Listener is ready");
     }
 }
Пример #8
0
 /// <summary>
 /// Wi-Fi直连广播者开始广播
 /// </summary>
 public void StartAdvertising()
 {
     publisher = new WiFiDirectAdvertisementPublisher();
     listener  = new WiFiDirectConnectionListener();
     publisher.StatusChanged += OnPublisherStatusChanged;
     publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Intensive;
     listener.ConnectionRequested += OnConnectionRequested;
     publisher.Start();
     //TextBlock_ConnectedState.Text = "开始广播……";
 }
Пример #9
0
 private void StartListener()
 {
     _listener = new WiFiDirectConnectionListener();
     try
     {
         _listener.ConnectionRequested += OnConnectionRequested;
     }
     catch (Exception ex)
     {
         return;
     }
 }
 public void StartServer()
 {
     publisher = new WiFiDirectAdvertisementPublisher();
     listener = new WiFiDirectConnectionListener();
     publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
     listener.ConnectionRequested += OnConnectionRequested;
     _ConnectionEstablishState = ConnectionEstablishState.Connecting;
     OnConnectionEstalblishResult(this, _ConnectionEstablishState);
     publisher.Start();
     StartUDP(50001);
     //TextBlock_ConnectedState.Text = "开始广播……";
 }
Пример #11
0
        private static void StartWiFiHotspot()
        {
            wifiPublisher          = new WiFiDirectAdvertisementPublisher();
            wifiConnectionListener = new WiFiDirectConnectionListener();

            wifiConnectionListener.ConnectionRequested += WifiConnectionListener_ConnectionRequested;

            wifiPublisher.Advertisement.IsAutonomousGroupOwnerEnabled      = true;
            wifiPublisher.Advertisement.LegacySettings.Ssid                = SSID;
            wifiPublisher.Advertisement.LegacySettings.IsEnabled           = true;
            wifiPublisher.Advertisement.LegacySettings.Passphrase.Password = PASSWORD;
            wifiPublisher.StatusChanged += WifiPublisher_StatusChanged;
            wifiPublisher.Start();
        }
Пример #12
0
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
        {
            WiFiDirectConnectionRequest connectionRequest = args.GetConnectionRequest();
            bool success = await Dispatcher.RunTaskAsync(async() =>
            {
                return(await HandleConnectionRequestAsync(connectionRequest));
            });

            if (!success)
            {
                // Decline the connection request
                //rootPage.NotifyUserFromBackground($"Connection request from {connectionRequest.DeviceInformation.Name} was declined", NotifyType.ErrorMessage);
                connectionRequest.Dispose();
            }
        }
Пример #13
0
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
        {
            WiFiDirectConnectionRequest ConnectionRequest = args.GetConnectionRequest();

            // Prompt the user to accept/reject the connection request
            // If rejected, exit

            // Connect to the remote device
            WiFiDirectDevice wfdDevice = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);

            // Get the local and remote IP addresses
            IReadOnlyList <Windows.Networking.EndpointPair> EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            // Establish standard WinRT socket with above IP addresses
        }
        void advertise()
        {
            if (mAdvertiser == null)
            {
                mAdvertiser = new WiFiDirectAdvertisementPublisher();
            }

            if (mConnectionListener == null)
            {
                mConnectionListener = new WiFiDirectConnectionListener();
            }
            mConnectionListener.ConnectionRequested += OnConnectionRequested;
            mAdvertiser.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
            mAdvertiser.StatusChanged += OnStatusChanged;
            mAdvertiser.Start();
        }
Пример #15
0
        public void Init()
        {
            // Create an Advertisement Publisher
            WiFiDirectAdvertisementPublisher publisher = new WiFiDirectAdvertisementPublisher();

            // Turn on Listen state
            publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;

            // Register for connection requests
            WiFiDirectConnectionListener listener = new WiFiDirectConnectionListener();

            listener.ConnectionRequested += OnConnectionRequested;

            // Start the advertiser
            publisher.Start();
        }
        private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_publisher == null)
                {
                    _publisher = new WiFiDirectAdvertisementPublisher();
                }

                if (chkListener.IsChecked == true)
                {
                    if (_listener == null)
                    {
                        _listener = new WiFiDirectConnectionListener();
                    }

                    _listener.ConnectionRequested += OnConnectionRequested;
                }

                _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = (chkPreferGroupOwnerMode.IsChecked == true);

                if (cmbListenState.SelectionBoxItem.ToString().Equals("Normal") == true)
                {
                    _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
                }
                else if (cmbListenState.SelectionBoxItem.ToString().Equals("Intensive") == true)
                {
                    _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Intensive;
                }
                else if (cmbListenState.SelectionBoxItem.ToString().Equals("None") == true)
                {
                    _publisher.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.None;
                }

                _publisher.StatusChanged += OnStatusChanged;

                _publisher.Start();

                rootPage.NotifyUser("Advertisement started, waiting for StatusChanged callback...", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Error starting Advertisement: " + ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Пример #17
0
        /// <summary>
        /// 广播者接收到请求连接消息后的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
        {
            try
            {
                WiFiDirectConnectionRequest ConnectionRequest = args.GetConnectionRequest();
                WiFiDirectDevice            wfdDevice         = await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id);

                //与之连接过的列表
                EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
                //StartUDPServer("50001");
                //EstablishSocketFromAdvertiser(EndpointPairs[0].LocalHostName, "50001");
                //Invoke(() => { TextBlock_ConnectedState.Text = "连接到" + EndpointPairs[0].LocalHostName.ToString(); });
            }
            catch (Exception exp)
            {
                Invoke(() => { TextBlock_ConnectedState.Text = exp.Message; });
            }
        }
Пример #18
0
 private void Reset()
 {
     if (_connectionListener != null)
     {
         _connectionListener.ConnectionRequested -= OnConnectionRequested;
     }
     if (_publisher != null)
     {
         _publisher.StatusChanged -= OnStatusChanged;
         if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Created ||
             _publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
         {
             _publisher.Stop();
         }
     }
     _connectionListener = null;
     _publisher          = null;
     _legacySettings     = null;
     _advertisement      = null;
     _connectedDevices.Clear();
 }
        void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            WiFiDirectDevice wfdDevice;

            try {
                var connectionRequest = connectionEventArgs.GetConnectionRequest();
                WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                connectionParams.GroupOwnerIntent = 15;
                wfdDevice = WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams).AsTask().Result;

                // Register for the ConnectionStatusChanged event handler
                wfdDevice.ConnectionStatusChanged         += OnConnectionStatusChanged;
                mConnected[extractMAC(wfdDevice.DeviceId)] = wfdDevice;
                mGroupOwner = true;
            } catch (Exception ex) {
                Debug.WriteLine("Connect operation threw an exception: " + ex.Message);
                wfdDevice = null;
            }
            if (wfdDevice != null)
            {
                OnConnectionStatusChanged(wfdDevice, null);
            }
        }
 public WiFiDirectConnectionListenerEvents(WiFiDirectConnectionListener This)
 {
     this.This = This;
 }
Пример #21
0
 private static void WifiConnectionListener_ConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
 {
     Debug.WriteLine("ConnRequested: " + args.GetConnectionRequest().DeviceInformation.Id);
     UDPServer.Current.MessageReceived += Current_MessageReceived;
 }
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            try
            {
                var connectionRequest = connectionEventArgs.GetConnectionRequest();

                var tcs = new TaskCompletionSource<bool>();
                var dialogTask = tcs.Task;
                var messageDialog = new MessageDialog("Connection request received from " + connectionRequest.DeviceInformation.Name, "Connection Request");

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers 
                messageDialog.Commands.Add(new UICommand("Accept", null, 0));
                messageDialog.Commands.Add(new UICommand("Decline", null, 1));

                // Set the command that will be invoked by default 
                messageDialog.DefaultCommandIndex = 1;

                // Set the command to be invoked when escape is pressed 
                messageDialog.CancelCommandIndex = 1;

                await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                {
                    // Show the message dialog 
                    var commandChosen = await messageDialog.ShowAsync();

                    tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
                });

                var fProceed = await dialogTask;

                if (fProceed == true)
                {
                    var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
                    var wfdDeviceTask = tcsWiFiDirectDevice.Task;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
                    {
                        try
                        {
                            rootPage.NotifyUser("Connecting to " + connectionRequest.DeviceInformation.Name + "...", NotifyType.StatusMessage);

                            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                            connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);

                            // IMPORTANT: FromIdAsync needs to be called from the UI thread
                            tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams));
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser("FromIdAsync task threw an exception: " + ex.ToString(), NotifyType.ErrorMessage);
                        }
                    });

                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Register for the ConnectionStatusChanged event handler
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        ConnectedDevice connectedDevice = new ConnectedDevice("Waiting for client to connect...", wfdDevice, null);
                        _connectedDevices.Add(connectedDevice);
                    });

                    var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    _listenerSocket = null;
                    _listenerSocket = new StreamSocketListener();
                    _listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
                    await _listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);

                    rootPage.NotifyUserFromBackground("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() +
                                            " Port: " + Globals.strServerPort, NotifyType.StatusMessage);
                }
                else
                {
                    // Decline the connection request
                    rootPage.NotifyUserFromBackground("Connection request from " + connectionRequest.DeviceInformation.Name + " was declined", NotifyType.ErrorMessage);
                    connectionRequest.Dispose();
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUserFromBackground("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
 private void ListenForIncomingConnections()
 {
     _listener = new WiFiDirectConnectionListener();
     _listener.ConnectionRequested += OnConnectionRequested;
 }
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
            bool success = await Dispatcher.RunTaskAsync(async () =>
            {
                return await HandleConnectionRequestAsync(connectionRequest);
            });

            if (!success)
            {
                // Decline the connection request
                rootPage.NotifyUserFromBackground($"Connection request from {connectionRequest.DeviceInformation.Name} was declined", NotifyType.ErrorMessage);
                connectionRequest.Dispose();
            }
        }
Пример #25
0
        private async void OnConnectionRequested(WiFiDirectConnectionListener listener, WiFiDirectConnectionRequestedEventArgs eventArgs)
        {
            if (_listener != null)
            {
                _listener.LogMessage("Connection Requested...");
            }
            bool acceptConnection = true;

            if (!AutoAccept && _prompt != null)
            {
                acceptConnection = _prompt.AcceptIncommingConnection();
            }

            try
            {
                WiFiDirectConnectionRequest request = eventArgs.GetConnectionRequest();
                if (acceptConnection)
                {
                    DeviceInformation deviceInformation = request.DeviceInformation;
                    string            deviceId          = deviceInformation.Id;

                    // Must call FromIdAsync first
                    var tcsWiFiDirectDevice = new TaskCompletionSource <WiFiDirectDevice>();
                    var wfdDeviceTask       = tcsWiFiDirectDevice.Task;
                    tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(deviceId));
                    // Get the WiFiDirectDevice object
                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Now retrieve the endpoint pairs, which includes the IP address assigned to the peer
                    var    endpointPairs  = wfdDevice.GetConnectionEndpointPairs();
                    string remoteHostName = "";
                    if (endpointPairs.Any())
                    {
                        EndpointPair endpoint = endpointPairs[0];
                        remoteHostName = endpoint.RemoteHostName.DisplayName;
                    }
                    else
                    {
                        throw new Exception("Can't retrieve endpoint pairs");
                    }

                    // Add handler for connection status changed
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    // Store the connected peer
                    lock (_threadObject)
                    {
                        _connectedDevices.Add(wfdDevice.DeviceId, wfdDevice);
                    }

                    // Notify Listener
                    if (_listener != null)
                    {
                        _listener.OnDeviceConnected(remoteHostName);
                    }
                }
                else
                {
                    if (_listener != null)
                    {
                        _listener.LogMessage("Declined");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_listener != null)
                {
                    _listener.OnAsyncException(ex.ToString());
                }
                return;
            }
        }
        private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
        {
            try
            {
                var connectionRequest = connectionEventArgs.GetConnectionRequest();

                var tcs           = new TaskCompletionSource <bool>();
                var dialogTask    = tcs.Task;
                var messageDialog = new MessageDialog("Connection request received from " + connectionRequest.DeviceInformation.Name, "Connection Request");

                // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
                messageDialog.Commands.Add(new UICommand("Accept", null, 0));
                messageDialog.Commands.Add(new UICommand("Decline", null, 1));

                // Set the command that will be invoked by default
                messageDialog.DefaultCommandIndex = 1;

                // Set the command to be invoked when escape is pressed
                messageDialog.CancelCommandIndex = 1;

                await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
                {
                    // Show the message dialog
                    var commandChosen = await messageDialog.ShowAsync();

                    tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
                });

                var fProceed = await dialogTask;

                if (fProceed == true)
                {
                    var tcsWiFiDirectDevice = new TaskCompletionSource <WiFiDirectDevice>();
                    var wfdDeviceTask       = tcsWiFiDirectDevice.Task;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
                    {
                        try
                        {
                            rootPage.NotifyUser("Connecting to " + connectionRequest.DeviceInformation.Name + "...", NotifyType.StatusMessage);

                            WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
                            connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text);

                            // IMPORTANT: FromIdAsync needs to be called from the UI thread
                            tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams));
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser("FromIdAsync task threw an exception: " + ex.ToString(), NotifyType.ErrorMessage);
                        }
                    });

                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Register for the ConnectionStatusChanged event handler
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        ConnectedDevice connectedDevice = new ConnectedDevice("Waiting for client to connect...", wfdDevice, null);
                        _connectedDevices.Add(connectedDevice);
                    });

                    var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    _listenerSocket = null;
                    _listenerSocket = new StreamSocketListener();
                    _listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
                    await _listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);

                    rootPage.NotifyUserFromBackground("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() +
                                                      " Port: " + Globals.strServerPort, NotifyType.StatusMessage);
                }
                else
                {
                    // Decline the connection request
                    rootPage.NotifyUserFromBackground("Connection request from " + connectionRequest.DeviceInformation.Name + " was declined", NotifyType.ErrorMessage);
                    connectionRequest.Dispose();
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUserFromBackground("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
        private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new WiFiDirectAdvertisementPublisher();
            _publisher.StatusChanged += OnStatusChanged;

            _listener = new WiFiDirectConnectionListener();

            if (chkListener.IsChecked.Value)
            {
                try
                {
                    // This can raise an exception if the machine does not support WiFi. Sorry.
                    _listener.ConnectionRequested += OnConnectionRequested;
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser($"Error preparing Advertisement: {ex}", NotifyType.ErrorMessage);
                    return;
                }
            }

            var discoverability = Utils.GetSelectedItemTag<WiFiDirectAdvertisementListenStateDiscoverability>(cmbListenState);
            _publisher.Advertisement.ListenStateDiscoverability = discoverability;

            _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = chkPreferGroupOwnerMode.IsChecked.Value;

            // Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
            if (_publisher.Advertisement.IsAutonomousGroupOwnerEnabled && chkLegacySetting.IsChecked.Value)
            {
                _publisher.Advertisement.LegacySettings.IsEnabled = true;
                if (!String.IsNullOrEmpty(txtPassphrase.Text))
                {
                    var creds = new Windows.Security.Credentials.PasswordCredential();
                    creds.Password = txtPassphrase.Text;
                    _publisher.Advertisement.LegacySettings.Passphrase = creds;
                }

                if (!String.IsNullOrEmpty(txtSsid.Text))
                {
                    _publisher.Advertisement.LegacySettings.Ssid = txtSsid.Text;
                }
            }

            // Add the information elements.
            foreach (WiFiDirectInformationElement informationElement in _informationElements)
            {
                _publisher.Advertisement.InformationElements.Add(informationElement);
            }

            _publisher.Start();

            if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
            {
                btnStartAdvertisement.IsEnabled = false;
                btnStopAdvertisement.IsEnabled = true;
                rootPage.NotifyUser("Advertisement started.", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser($"Advertisement failed to start. Status is {_publisher.Status}", NotifyType.ErrorMessage);
            }
        }