public void Reset()
        {
            PeerFinder.Stop();
            StopInitBrowseWpToWin();

            if (dataReader != null)
            {
                try
                {
                    listening = false;
                    if (dataReader != null)
                    {
                        dataReader.Dispose();
                        dataReader = null;
                    }
                    if (dataWriter != null)
                    {
                        dataWriter.Dispose();
                        dataWriter = null;
                    }
                    if (socket != null)
                    {
                        socket.Dispose();
                        socket = null;
                    }
                }
                catch (Exception)
                {
                }
            }
        }
예제 #2
0
 protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
 {
     StopWatching();
     PeerFinder.Stop();
     PeerFinder.ConnectionRequested -= ConnectionRequested;
     base.OnNavigatingFrom(e);
 }
예제 #3
0
        private void CloseConnection(bool continueAdvertise)
        {
            if (_dataReader != null)
            {
                _dataReader.Dispose();
                _dataReader = null;
            }

            if (_dataWriter != null)
            {
                _dataWriter.Dispose();
                _dataWriter = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            if (continueAdvertise)
            {
                // Since there is no connection, let's advertise ourselves again, so that peers can find us.
                PeerFinder.Start();
            }
            else
            {
                PeerFinder.Stop();
            }
        }
예제 #4
0
        private static StreamSocket RunAsServer(string localPeerDisplayName, string remotePeerDisplayName)
        {
            PeerFinder.DisplayName          = localPeerDisplayName;
            PeerFinder.AllowInfrastructure  = false;
            PeerFinder.AllowBluetooth       = false;
            PeerFinder.AllowWiFiDirect      = true;
            PeerFinder.ConnectionRequested += (sender, e) =>
            {
                if (e.PeerInformation.DisplayName == remotePeerDisplayName)
                {
                    SetRemotePeerInformation(e.PeerInformation);
                }
            };
            PeerFinder.Start();

            Task <StreamSocket> task = Task.Run(() =>
            {
                return((MResetEvent.WaitOne(30000))
                ? PeerFinder.ConnectAsync(RemotePeerInformation).AsTask().Result
                : throw new Exception("Listen Timeout"));
            });

            EllipsisAnimation(task.Wait, "Listening");

            PeerFinder.Stop();
            return(task.Result);
        }
예제 #5
0
        void TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs e)
        {
            switch (e.State)
            {
            case TriggeredConnectState.PeerFound:
                UpdateConnectionStatus(ConnectionStatus.PeerFound);
                break;

            case TriggeredConnectState.Canceled:
                UpdateConnectionStatus(ConnectionStatus.Canceled);
                break;

            case TriggeredConnectState.Failed:
                UpdateConnectionStatus(ConnectionStatus.Failed);
                break;

            case TriggeredConnectState.Completed:
                StartSendReceive(e.Socket);
                UpdateConnectionStatus(ConnectionStatus.Completed);

                // Stop advertising since we have connected
                PeerFinder.Stop();
                _peerFinderStarted = false;
                break;
            }
        }
예제 #6
0
        private static StreamSocket RunAsClient(string localPeerDisplayName, string remotePeerDisplayName)
        {
            PeerFinder.DisplayName         = localPeerDisplayName;
            PeerFinder.AllowInfrastructure = false;
            PeerFinder.AllowBluetooth      = false;
            PeerFinder.AllowWiFiDirect     = true;
            PeerFinder.Start();
            PeerWatcher watcher = PeerFinder.CreateWatcher();

            watcher.Added += (sender, peerInfo) =>
            {
                if (peerInfo.DisplayName == remotePeerDisplayName)
                {
                    SetRemotePeerInformation(peerInfo);
                }
            };
            watcher.Start();

            Task <StreamSocket> task = Task.Run(() =>
            {
                return((MResetEvent.WaitOne(30000))
                ? PeerFinder.ConnectAsync(RemotePeerInformation).AsTask().Result
                : throw new Exception("Connect Timeout"));
            });

            EllipsisAnimation(task.Wait, "Connecting");

            PeerFinder.Stop();
            return(task.Result);
        }
예제 #7
0
        // Invoked when the main page navigates to a different scenario
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            // If PeerFinder was started, stop it when navigating to a different page.
            if (_peerFinderStarted)
            {
                // detach the callback handler (there can only be one PeerConnectProgress handler).
                PeerFinder.TriggeredConnectionStateChanged -= new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler);
                // detach the incoming connection request event handler
                PeerFinder.ConnectionRequested -= new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested);
                PeerFinder.Stop();
                _socketHelper.CloseSocket();
                _peerFinderStarted = false;
            }
            if (_peerWatcher != null)
            {
                // unregister for events
                _peerWatcher.Added   -= PeerWatcher_Added;
                _peerWatcher.Removed -= PeerWatcher_Removed;
                _peerWatcher.Updated -= PeerWatcher_Updated;
                _peerWatcher.EnumerationCompleted -= PeerWatcher_EnumerationCompleted;
                _peerWatcher.Stopped -= PeerWatcher_Stopped;

                _peerWatcher = null;
            }
        }
예제 #8
0
        /// <summary>
        /// Closes existing Bluetooth connection.
        /// </summary>
        /// <param name="continueAdvertise">indicates whether the app should be discoverable to remote peers after closing connection. </param>
        private void CloseConnection(bool continueAdvertise)
        {
            PeerFinder.Stop();
            this.isListeningEnabled = false;

            if (dataReader != null)
            {
                dataReader.Dispose();
                dataReader = null;
            }

            if (dataWriter != null)
            {
                dataWriter.Dispose();
                dataWriter = null;
            }

            if (connectionSocket != null)
            {
                connectionSocket.Dispose();
                connectionSocket = null;
            }

            if (continueAdvertise)
            {
                PeerFinder.Start();
            }
        }
 private void DoConnect(StreamSocket receivedSocket)
 {
     socket = receivedSocket;
     StartListeningForMessages();
     PeerFinder.Stop();
     FireConnectionStatusChanged(TriggeredConnectState.Completed);
 }
예제 #10
0
        /// <summary>
        /// Disconnect currently active connections and/or stop listening to tap events.
        /// </summary>
        public void Stop()
        {
            PeerFinder.Stop();

            switch (_status)
            {
            case ConnectionStatusValue.Searching:
            case ConnectionStatusValue.Connecting:
            case ConnectionStatusValue.Listening:
            {
                PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
                PeerFinder.ConnectionRequested             -= ConnectionRequested;
            }
            break;

            case ConnectionStatusValue.Connected:
            {
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }
            }
            break;
            }

            _status = ConnectionStatusValue.Idle;
        }
예제 #11
0
        async void ConnectToPeer(PeerInformation peer)
        {
            try
            {
                _socket = await PeerFinder.ConnectAsync(peer);

                // We can preserve battery by not advertising our presence.
                PeerFinder.Stop();

                _peerName = peer.DisplayName;
                UpdateChatBox(AppResources.Msg_ChatStarted, true);

                // Since this is a chat, messages can be incoming and outgoing.
                // Listen for incoming messages.
                ListenForIncomingMessage();
            }
            catch (Exception ex)
            {
                // In this sample, we handle each exception by displaying it and
                // closing any outstanding connection. An exception can occur here if, for example,
                // the connection was refused, the connection timeout etc.
                MessageBox.Show(ex.Message);
                CloseConnection(false);
            }
        }
예제 #12
0
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            // Das Suchen nach Peers beenden
            PeerFinder.Stop();

            base.OnNavigatingFrom(e);
        }
예제 #13
0
        public void Reset()
        {
            NetworkConnectionStatus = NetworkConnectionState.NotSearching;
            PeerFinder.Stop();
            StopInitBrowseWpToWin();

            if (dataReader != null)
            {
                try
                {
                    listening = false;
                    if (dataReader != null)
                    {
                        dataReader.Dispose();
                        dataReader = null;
                    }
                    if (dataWriter != null)
                    {
                        dataWriter.Dispose();
                        dataWriter = null;
                    }
                    if (socket != null)
                    {
                        socket.Dispose();
                        socket = null;
                    }
                }
                catch (Exception)
                {
                }
            }
        }
예제 #14
0
파일: MainPage.xaml.cs 프로젝트: ckc/WinApp
        public MainPage()
        {
            InitializeComponent();
            PeerFinder.Stop();

            SizeChanged += OnWindowSizeChanged;
        }
예제 #15
0
        async void ConnectToPeer(PeerInformation peer)
        {
            try
            {
                _socket = await PeerFinder.ConnectAsync(peer);

                if (_dataReader == null)
                {
                    _dataReader = new DataReader(_socket.InputStream);
                }

                // We can preserve battery by not advertising our presence.
                PeerFinder.Stop();

                _peerName = peer.DisplayName;
                //UpdateChatBox(AppResources.Msg_ChatStarted, true);

                connected = true;
                // Listen for incoming messages.
                ListenForIncomingMessage();
            }
            catch (Exception ex)
            {
                // In this sample, we handle each exception by displaying it and
                // closing any outstanding connection. An exception can occur here if, for example,
                // the connection was refused, the connection timeout etc.
                MessageBox.Show(ex.Message);
            }
        }
예제 #16
0
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            reading = false;
            PeerFinder.Stop();

            base.OnNavigatedFrom(e);
        }
예제 #17
0
        /// <summary>
        /// Stop advertising for a peer connection
        /// </summary>
        public void StopConnect()
        {
            PeerFinder.Stop();
            CloseSocket();
            _peerFinderStarted = false;

            UpdateConnectionStatus(ConnectionStatus.Disconnected);
        }
예제 #18
0
 private void GoBack(object sender, RoutedEventArgs e)
 {
     PeerFinder.Stop();
     if (Frame != null && Frame.CanGoBack)
     {
         Frame.GoBack();
     }
 }
예제 #19
0
        // Handles PeerFinder_StopAdvertiseButton click
        void PeerFinder_StopAdvertising(object sender, RoutedEventArgs e)
        {
            if (_peerFinderStarted)
            {
                PeerFinder.Stop();
                _peerFinderStarted = false;

                rootPage.NotifyUser("Stopped Advertising.", NotifyType.StatusMessage);
                ToggleWatcherControls(false);
            }
        }
예제 #20
0
 protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
 {
     if (_started)
     {
         // Detach the callback handler (there can only be one PeerConnectProgress handler).
         PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
         // Detach the incoming connection request event handler.
         PeerFinder.Stop();
         CloseSocket();
         _started = false;
     }
 }
예제 #21
0
        public static async void ConnectToPeer(PeerInformation peer)
        {
            try {
                socket = await PeerFinder.ConnectAsync(peer);

                PeerFinder.Stop();
                ListenForIncomingCommand();
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
 // Invoked when the main page navigates to a different scenario
 protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
 {
     if (_peerFinderStarted)
     {
         // detach the callback handler (there can only be one PeerConnectProgress handler).
         PeerFinder.TriggeredConnectionStateChanged -= new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler);
         // detach the incoming connection request event handler
         PeerFinder.ConnectionRequested -= new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested);
         PeerFinder.Stop();
         CloseSocket();
         _peerFinderStarted = false;
     }
 }
예제 #23
0
        // Handles PeerFinder_StopAdvertiseButton click
        void PeerFinder_StopAdvertising(object sender, RoutedEventArgs e)
        {
            if (_peerFinderStarted)
            {
                PeerFinder.Stop();
                _peerFinderStarted = false;

                rootPage.NotifyUser("Stopped Advertising.", NotifyType.StatusMessage);
                PeerFinder_StopAdvertiseButton.Visibility = Visibility.Collapsed;
                PeerFinder_BrowseGrid.Visibility          = Visibility.Collapsed;
                PeerFinder_ConnectButton.Visibility       = Visibility.Collapsed;
            }
        }
예제 #24
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        private async void LoadState(Object navigationParameter, Dictionary <String, Object> pageState)
        {
            // Users wait (i.e. watch progress) on this page until the connection has succeeded/failed.
            backButton.Visibility = Visibility.Collapsed;
            if (navigationParameter != null)
            {
                WaitingForHostParameters parameters = (WaitingForHostParameters)navigationParameter;
                if (parameters.Peer != null)
                {
                    pageTitle.Text = "Connecting to " + parameters.Peer.DisplayName.ToString() + "...";
                    try
                    {
                        StreamSocket socket = await PeerFinder.ConnectAsync(parameters.Peer);

                        pageTitle.Text = "Connected! Waiting for Host...";
                        this.socket    = new SocketReaderWriter(socket, this);
                        ConnectedPeer tempPeer = new ConnectedPeer(parameters.Peer.DisplayName);
                        connectedPeers[tempPeer] = this.socket;

                        PeerFinder.Stop();
                        StartReading();
                    }
                    catch (Exception)
                    {
                        pageTitle.Text = "Cannot connect to " + parameters.Peer.DisplayName;
                        PeerFinder.Stop();
                    }
                    progressBar.Visibility = Visibility.Collapsed;
                    backButton.Visibility  = Visibility.Visible;
                }
                else if (parameters.Socket != null)
                {
                    try
                    {
                        this.socket    = new SocketReaderWriter(parameters.Socket, this);
                        pageTitle.Text = "Waiting for Host...";
                        socket.WriteMessage(string.Format("{0} {1}", Constants.OpCodeSendDisplayName, PeerFinder.DisplayName));

                        PeerFinder.Stop();
                        StartReading();
                    }
                    catch (Exception)
                    {
                        pageTitle.Text = "Cannot connect";
                        PeerFinder.Stop();
                    }
                    backButton.Visibility  = Visibility.Visible;
                    progressBar.Visibility = Visibility.Collapsed;
                }
            }
        }
예제 #25
0
        /// <summary>
        /// Send personal information to windows 8 application.
        /// </summary>
        /// <param name="pInfo"></param>
        /// <returns></returns>
        public async void SendInfo(Visitor pInfo)
        {
            this.pInformation = pInfo;
            var content = JsonConvert.SerializeObject(pInformation);

            if (writer != null)
            {
                writer.WriteInt32(content.Length);
                writer.WriteString(content);
                await writer.StoreAsync();
            }
            PeerFinder.Stop();
            PeerFinder.Start();
        }
예제 #26
0
 public void CloseSocket()
 {
     // Host, client, and singlepair all close their sockets.
     if (gameMode == Constants.MultiPlayer)
     {
         if (PeerFinder.Role == PeerRole.Client)
         {
             socket.WriteMessage(string.Format("{0}", Message.Closing));
             socket.Dispose();
             connectedPeers = null;
             PeerFinder.Stop();
         }
     }
 }
예제 #27
0
        public void Dispose()
        {
            if (this.proximityDevice != null)
            {
                this.proximityDevice.DeviceDeparted -= this.ProximityDeviceDeviceDeparted;
                this.proximityDevice.DeviceArrived  -= this.ProximityDeviceDeviceArrived;
                this.proximityDevice = null;
            }

            this.DisposeSocket();

            if (this.isAdvertising)
            {
                PeerFinder.Stop();
            }
        }
예제 #28
0
        //Used to display state of the connection (i.e. connecting, connected, disconnected) when two PCs are tapped
        private async void TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs e)
        {
            if (e.State == TriggeredConnectState.PeerFound)
            {
                await messageDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    progressBar.Visibility = Visibility.Collapsed;
                    ReceivedInvitationsHeader.Visibility = Visibility.Collapsed;
                    receivedInvitations.Visibility       = Visibility.Collapsed;
                    backButton.Visibility = Visibility.Collapsed;

                    tapProgressBar.Visibility = Visibility.Visible;
                    tapConnectStatus.Text     = "Connecting to Host...";
                });
            }
            else if (e.State == TriggeredConnectState.Completed)
            {
                try
                {
                    await messageDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        StreamSocket socket       = e.Socket;
                        tapConnectStatus.Text     = "Connected!";
                        tapProgressBar.Visibility = Visibility.Collapsed;
                        WaitForHost(socket);
                    });
                }
                catch (Exception)
                {
                    tapConnectStatus.Text     = "Cannot connect";
                    tapProgressBar.Visibility = Visibility.Collapsed;
                    PeerFinder.Stop();
                    backButton.Visibility = Visibility.Visible;
                }
            }
            else if (e.State == TriggeredConnectState.Failed)
            {
                await messageDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    tapConnectStatus.Text = "Cannot connect";
                    PeerFinder.Stop();
                    backButton.Visibility     = Visibility.Visible;
                    tapProgressBar.Visibility = Visibility.Collapsed;
                });
            }
        }
예제 #29
0
        private void CloseConnection(bool continueAdvertise)
        {
            if (App.linkSocket != null)
            {
                App.linkSocket.Dispose();
                App.linkSocket = null;
            }

            if (continueAdvertise)
            {
                // Since there is no connection, let's advertise ourselves again, so that peers can find us.
                PeerFinder.Start();
            }
            else
            {
                PeerFinder.Stop();
            }
        }
예제 #30
0
        async void ConnectToPeer(PeerInformation peer)
        {
            try
            {
                App.linkSocket = await PeerFinder.ConnectAsync(peer);

                // We can preserve battery by not advertising our presence.
                PeerFinder.Stop();
            }
            catch (Exception ex)
            {
                // In this sample, we handle each exception by displaying it and
                // closing any outstanding connection. An exception can occur here if, for example,
                // the connection was refused, the connection timeout etc.
                MessageBox.Show(ex.Message);
                CloseConnection(false);
            }
        }