private void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                rootPage.NotifyUser("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
                StreamSocket serverSocket = args.Socket;

                SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, rootPage);
                // The first message sent is the name of the connection.
                string message = await socketRW.ReadMessageAsync();

                // Find the pending connection and add it to the list of active connections.
                WiFiDirectDevice wfdDevice;
                if (_pendingConnections.TryRemove(sender, out wfdDevice))
                {
                    ConnectedDevices.Add(new ConnectedDevice(message, wfdDevice, socketRW));
                }

                /*
                 * while (message != null)
                 * {
                 *  message = await socketRW.ReadMessageAsync();
                 * }
                 */
                while (await socketRW.ReadFileAsync() != null)
                {
                    // Keep reading messages
                }
            });
        }
        private void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                rootPage.NotifyUser("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
                StreamSocket serverSocket = args.Socket;

                // Look up the WiFiDirectDevice associated with this StreamSocketListener.
                WiFiDirectDevice wfdDevice;
                if (!_pendingConnections.TryRemove(sender, out wfdDevice))
                {
                    rootPage.NotifyUser("Unexpected connection ignored.", NotifyType.ErrorMessage);
                    serverSocket.Dispose();
                    return;
                }

                SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, rootPage);

                // The first message sent is the name of the connection.
                string message = await socketRW.ReadMessageAsync();

                // Add this connection to the list of active connections.
                ConnectedDevices.Add(new ConnectedDevice(message ?? "(unnamed)", wfdDevice, socketRW));

                while (message != null)
                {
                    message = await socketRW.ReadMessageAsync();
                }
            });
        }
        private async void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            rootPage.NotifyUserFromBackground("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
            StreamSocket serverSocket = args.Socket;

            try
            {
                SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, rootPage);
                socketRW.ReadMessage();

                while (true)
                {
                    string sessionId = socketRW.GetCurrentMessage();
                    if (sessionId != null)
                    {
                        rootPage.NotifyUserFromBackground("Connected with remote side on L4 layer", NotifyType.StatusMessage);

                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            for (int idx = 0; idx < _connectedDevices.Count; idx++)
                            {
                                if (_connectedDevices[idx].DisplayName.Equals("Waiting for client to connect...") == true)
                                {
                                    ConnectedDevice connectedDevice = _connectedDevices[idx];
                                    _connectedDevices.RemoveAt(idx);

                                    connectedDevice.DisplayName = sessionId;
                                    connectedDevice.SocketRW    = socketRW;

                                    _connectedDevices.Add(connectedDevice);
                                    break;
                                }
                            }
                        });


                        break;
                    }

                    await Task.Delay(100);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUserFromBackground("Connection failed: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     this.socketRW = socketRW;
     this.wfdDevice = wfdDevice;
     this.displayName = displayName;
 }
        private async void btnFromId_Click(object sender, RoutedEventArgs e)
        {
            var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem;

            if (discoveredDevice == null)
            {
                rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
                return;
            }

            rootPage.NotifyUser($"Connecting to {discoveredDevice.DeviceInfo.Name}...", NotifyType.StatusMessage);

            if (!discoveredDevice.DeviceInfo.Pairing.IsPaired)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(discoveredDevice.DeviceInfo.Pairing))
                {
                    return;
                }
            }

            WiFiDirectDevice wfdDevice = null;

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id);
            }
            catch (TaskCanceledException)
            {
                rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
                return;
            }

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

            IReadOnlyList <EndpointPair> endpointPairs = wfdDevice.GetConnectionEndpointPairs();
            HostName remoteHostName = endpointPairs[0].RemoteHostName;

            rootPage.NotifyUser($"Devices connected on L2 layer, connecting to IP Address: {remoteHostName} Port: {Globals.strServerPort}",
                                NotifyType.StatusMessage);

            // Wait for server to start listening on a socket
            await Task.Delay(2000);

            // Connect to Advertiser on L4 layer
            StreamSocket clientSocket = new StreamSocket();

            try
            {
                await clientSocket.ConnectAsync(remoteHostName, Globals.strServerPort);

                rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
                return;
            }

            SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

            string          sessionId       = Path.GetRandomFileName();
            ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);

            ConnectedDevices.Add(connectedDevice);

            // The first message sent over the socket is the name of the connection.
            await socketRW.WriteMessageAsync(sessionId);

            while (await socketRW.ReadMessageAsync() != null)
            {
                // Keep reading messages
            }
        }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     DisplayName = displayName;
     WfdDevice = wfdDevice;
     SocketRW = socketRW;
 }
        private async void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            rootPage.NotifyUserFromBackground("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
            StreamSocket serverSocket = args.Socket;

            try
            {
                SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, rootPage);
                socketRW.ReadMessage();

                while (true)
                {
                    string sessionId = socketRW.GetCurrentMessage();
                    if (sessionId != null)
                    {
                        rootPage.NotifyUserFromBackground("Connected with remote side on L4 layer", NotifyType.StatusMessage);

                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            for (int idx = 0; idx < _connectedDevices.Count; idx++)
                            {
                                if (_connectedDevices[idx].DisplayName.Equals("Waiting for client to connect...") == true)
                                {
                                    ConnectedDevice connectedDevice = _connectedDevices[idx];
                                    _connectedDevices.RemoveAt(idx);

                                    connectedDevice.DisplayName = sessionId;
                                    connectedDevice.SocketRW = socketRW;

                                    _connectedDevices.Add(connectedDevice);
                                    break;
                                }
                            }
                        });


                        break;
                    }

                    await Task.Delay(100);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUserFromBackground("Connection failed: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     DisplayName = displayName;
     WfdDevice   = wfdDevice;
     SocketRW    = socketRW;
 }
 public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
 {
     this.socketRW    = socketRW;
     this.wfdDevice   = wfdDevice;
     this.displayName = displayName;
 }
        private async void btnFromId_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (lvDiscoveredDevices.SelectedItems.Count == 0)
            {
                rootPage.NotifyUser("No device selected, please select atleast one.", NotifyType.ErrorMessage);
                return;
            }

            var selectedDevices = lvDiscoveredDevices.SelectedItems;

            foreach (DiscoveredDevice discoveredDevice in selectedDevices)
            {
                rootPage.NotifyUser("Connecting to " + discoveredDevice.DeviceInfo.Name + "...", NotifyType.StatusMessage);

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

                    _cancellationTokenSource = new CancellationTokenSource();

                    // IMPORTANT: FromIdAsync needs to be called from the UI thread
                    var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id, connectionParams).AsTask(_cancellationTokenSource.Token);

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

                    var endpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    rootPage.NotifyUser("Devices connected on L2 layer, connecting to IP Address: " + endpointPairs[0].RemoteHostName +
                                        " Port: " + Globals.strServerPort, NotifyType.StatusMessage);

                    // Wait for server to start listening on a socket
                    await Task.Delay(2000);

                    // Connect to Advertiser on L4 layer
                    StreamSocket clientSocket = new StreamSocket();
                    await clientSocket.ConnectAsync(endpointPairs[0].RemoteHostName, Globals.strServerPort);

                    SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

                    string sessionId = "Session: " + Path.GetRandomFileName();
                    ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
                    _connectedDevices.Add(connectedDevice);

                    socketRW.ReadMessage();
                    socketRW.WriteMessage(sessionId);

                    rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
                }
                catch (TaskCanceledException)
                {
                    rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
                }

                _cancellationTokenSource = null;
            }
        }
        private async void btnFromId_Click(object sender, RoutedEventArgs e)
        {
            var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem;

            if (discoveredDevice == null)
            {
                rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
                return;
            }

            rootPage.NotifyUser($"Connecting to {discoveredDevice.DeviceInfo.Name}...", NotifyType.StatusMessage);

            if (!discoveredDevice.DeviceInfo.Pairing.IsPaired)
            {
                if (!await connectionSettingsPanel.RequestPairDeviceAsync(discoveredDevice.DeviceInfo.Pairing))
                {
                    return;
                }
            }

            try
            {
                // IMPORTANT: FromIdAsync needs to be called from the UI thread
                var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id);

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

                IReadOnlyList<EndpointPair> endpointPairs = wfdDevice.GetConnectionEndpointPairs();
                HostName remoteHostName = endpointPairs[0].RemoteHostName;

                rootPage.NotifyUser($"Devices connected on L2 layer, connecting to IP Address: {remoteHostName} Port: {Globals.strServerPort}",
                    NotifyType.StatusMessage);

                // Wait for server to start listening on a socket
                await Task.Delay(2000);

                // Connect to Advertiser on L4 layer
                StreamSocket clientSocket = new StreamSocket();
                await clientSocket.ConnectAsync(remoteHostName, Globals.strServerPort);
                rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);

                SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

                string sessionId = Path.GetRandomFileName();
                ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
                ConnectedDevices.Add(connectedDevice);

                // The first message sent over the socket is the name of the connection.
                await socketRW.WriteMessageAsync(sessionId);

                while (await socketRW.ReadMessageAsync() != null)
                {
                    // Keep reading messages
                }

            }
            catch (TaskCanceledException)
            {
                rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
            }
        }
        private void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                rootPage.NotifyUser("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
                StreamSocket serverSocket = args.Socket;

                SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, rootPage);
                // The first message sent is the name of the connection.
                string message = await socketRW.ReadMessageAsync();

                // Find the pending connection and add it to the list of active connections.
                WiFiDirectDevice wfdDevice;
                if (_pendingConnections.TryRemove(sender, out wfdDevice))
                {
                    ConnectedDevices.Add(new ConnectedDevice(message, wfdDevice, socketRW));
                }

                while (message != null)
                {
                    message = await socketRW.ReadMessageAsync();
                }
            });
        }
        private async void btnFromId_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (lvDiscoveredDevices.SelectedItems.Count == 0)
            {
                rootPage.NotifyUser("No device selected, please select atleast one.", NotifyType.ErrorMessage);
                return;
            }

            var selectedDevices = lvDiscoveredDevices.SelectedItems;

            foreach (DiscoveredDevice discoveredDevice in selectedDevices)
            {
                rootPage.NotifyUser("Connecting to " + discoveredDevice.DeviceInfo.Name + "...", NotifyType.StatusMessage);

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

                    _cancellationTokenSource = new CancellationTokenSource();

                    // IMPORTANT: FromIdAsync needs to be called from the UI thread
                    var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id, connectionParams).AsTask(_cancellationTokenSource.Token);

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

                    var endpointPairs = wfdDevice.GetConnectionEndpointPairs();

                    rootPage.NotifyUser("Devices connected on L2 layer, connecting to IP Address: " + endpointPairs[0].RemoteHostName +
                                        " Port: " + Globals.strServerPort, NotifyType.StatusMessage);

                    // Wait for server to start listening on a socket
                    await Task.Delay(2000);

                    // Connect to Advertiser on L4 layer
                    StreamSocket clientSocket = new StreamSocket();
                    await clientSocket.ConnectAsync(endpointPairs[0].RemoteHostName, Globals.strServerPort);

                    SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);

                    string          sessionId       = "Session: " + Path.GetRandomFileName();
                    ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
                    _connectedDevices.Add(connectedDevice);

                    socketRW.ReadMessage();
                    socketRW.WriteMessage(sessionId);

                    rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
                }
                catch (TaskCanceledException)
                {
                    rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage);
                }

                _cancellationTokenSource = null;
            }
        }