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