Exemple #1
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);
 }
Exemple #3
0
        private async Task <bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
        {
            string deviceName = connectionRequest.DeviceInformation.Name;

            bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) ||
                            (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id));

            //rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage);

            // Pair device if not already paired and not using legacy settings
            if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing))
                {
                    return(false);
                }
            }

            WiFiDirectDevice wfdDevice = null;

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);
            }
            catch (Exception ex)
            {
                //rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage);
                return(false);
            }

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

            StreamSocketListener listenerSocket = new StreamSocketListener();

            // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made.
            _pendingConnections[listenerSocket] = wfdDevice;

            IReadOnlyList <Windows.Networking.EndpointPair> EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
            try
            {
                await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);
            }
            catch (Exception ex)
            {
                //rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return(false);
            }

            //rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" +
            //$" Port: {Globals.strServerPort}", NotifyType.StatusMessage);
            return(true);
        }
Exemple #4
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();
            }
        }
Exemple #5
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
        }
Exemple #6
0
        private async void GetData(WiFiDirectConnectionRequest connectionRequest)
        {
            try
            {
                var wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);

                var    endPoint = wfdDevice.GetConnectionEndpointPairs();
                string result   = string.Empty;
                foreach (var item in endPoint)
                {
                    result = item.LocalHostName + "\r\n";
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemple #7
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; });
            }
        }
Exemple #8
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 Task <bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
        {
            string deviceName = connectionRequest.DeviceInformation.Name;

            bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) ||
                            (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id));

            // Show the prompt only in case of WiFiDirect reconnection or Legacy client connection.
            if (isPaired || _publisher.Advertisement.LegacySettings.IsEnabled)
            {
                var messageDialog = new MessageDialog($"Connection request received from {deviceName}", "Connection Request");

                // Add two commands, distinguished by their tag.
                // The default command is "Decline", and if the user cancels, we treat it as "Decline".
                messageDialog.Commands.Add(new UICommand("Accept", null, true));
                messageDialog.Commands.Add(new UICommand("Decline", null, null));
                messageDialog.DefaultCommandIndex = 1;
                messageDialog.CancelCommandIndex  = 1;

                // Show the message dialog
                var commandChosen = await messageDialog.ShowAsync();

                if (commandChosen.Id == null)
                {
                    return(false);
                }
            }

            rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage);

            // Pair device if not already paired and not using legacy settings
            if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing))
                {
                    return(false);
                }
            }

            WiFiDirectDevice wfdDevice = null;

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage);
                return(false);
            }

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

            var listenerSocket = new StreamSocketListener();

            // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made.
            _pendingConnections[listenerSocket] = wfdDevice;

            var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            listenerSocket.ConnectionReceived += this.OnSocketConnectionReceived;
            try
            {
                await listenerSocket.BindServiceNameAsync(Globals.strServerPort);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return(false);
            }

            rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" +
                                $" Port: {Globals.strServerPort}", NotifyType.StatusMessage);


            return(true);
        }
        private async Task<bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
        {
            string deviceName = connectionRequest.DeviceInformation.Name;

            bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) ||
                            (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id));

            // Show the prompt only in case of WiFiDirect reconnection or Legacy client connection.
            if (isPaired || _publisher.Advertisement.LegacySettings.IsEnabled)
            {
                var messageDialog = new MessageDialog($"Connection request received from {deviceName}", "Connection Request");

                // Add two commands, distinguished by their tag.
                // The default command is "Decline", and if the user cancels, we treat it as "Decline".
                messageDialog.Commands.Add(new UICommand("Accept", null, true));
                messageDialog.Commands.Add(new UICommand("Decline", null, null));
                messageDialog.DefaultCommandIndex = 1;
                messageDialog.CancelCommandIndex = 1;

                // Show the message dialog
                var commandChosen = await messageDialog.ShowAsync();

                if (commandChosen.Id == null)
                {
                    return false;
                }
            }

            rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage);

            // Pair device if not already paired and not using legacy settings
            if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing))
                {
                    return false;
                }
            }

            WiFiDirectDevice wfdDevice = null;
            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage);
                return false;
            }

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

            var listenerSocket = new StreamSocketListener();

            // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made.
            _pendingConnections[listenerSocket] = wfdDevice;

            var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();

            listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
            try
            {
                await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return false;
            }

            rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" +
                                $" Port: {Globals.strServerPort}", NotifyType.StatusMessage);
            return true;
        }