Example #1
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);
        }
        // Handles PeerFinder_ConnectButton click
        async void PeerFinder_Connect(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            PeerInformation peerToConnect = null;

            if (PeerFinder_FoundPeersList.Items.Count == 0)
            {
                rootPage.NotifyUser("Cannot connect, there were no peers found!", NotifyType.ErrorMessage);
            }
            else
            {
                try
                {
                    peerToConnect = (PeerInformation)((ComboBoxItem)PeerFinder_FoundPeersList.SelectedItem).Tag;
                    if (peerToConnect == null)
                    {
                        peerToConnect = (PeerInformation)((ComboBoxItem)PeerFinder_FoundPeersList.Items[0]).Tag;
                    }

                    rootPage.NotifyUser("Connecting to " + peerToConnect.DisplayName + "....", NotifyType.StatusMessage);
                    StreamSocket socket = await PeerFinder.ConnectAsync(peerToConnect);

                    rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage);
                    PeerFinder_StartSendReceive(socket, peerToConnect);
                }
                catch (Exception err)
                {
                    rootPage.NotifyUser("Connection to " + peerToConnect.DisplayName + " failed: " + err.Message, NotifyType.ErrorMessage);
                }
            }
        }
Example #3
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);
            }
        }
Example #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);
        }
Example #5
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);
            }
        }
        async void PeerFinder_Connect(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            PeerInformation peerToConnect = null;

            try
            {
                // If nothing is selected, select the first peer
                if (PeerFinder_FoundPeersList.SelectedIndex == -1)
                {
                    peerToConnect = _peerInformationList[0];
                }
                else
                {
                    peerToConnect = _peerInformationList[PeerFinder_FoundPeersList.SelectedIndex];
                }

                rootPage.NotifyUser("Connecting to " + peerToConnect.DisplayName + "....", NotifyType.StatusMessage);
                StreamSocket socket = await PeerFinder.ConnectAsync(peerToConnect);

                rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage);
                PeerFinder_StartSendReceive(socket);
            }
            catch (Exception err)
            {
                rootPage.NotifyUser("Connection to " + peerToConnect.DisplayName + " failed: " + err.Message, NotifyType.ErrorMessage);
            }
        }
        private void DoConnect(PeerInformation peerInformation)
        {
            if (IsWindowsPhone)
            {
                var hostName = (HostName)peerInformation.GetType().GetRuntimeProperty("HostName").GetMethod.Invoke(peerInformation, null);
                if (hostName != null)
                {
                    var serviceName = (string)peerInformation.GetType().GetRuntimeProperty("ServiceName").GetMethod.Invoke(peerInformation, null);
                    DoConnect(hostName, "{" + rfcommServiceUuid.ToString().ToUpperInvariant() + "}");
                    return;
                }
            }

            PeerFinder.ConnectAsync(peerInformation).AsTask().ContinueWith(p =>
            {
                if (!p.IsFaulted)
                {
                    DoConnect(p.Result);
                }
                else
                {
                    Debug.WriteLine("connection fault");
                    FireConnectionStatusChanged(TriggeredConnectState.Failed);
                }
            });
        }
Example #8
0
        private async Task ConnectToPeers(PeerInformation peer)
        {
            try
            {
                progressBar.Visibility = Visibility.Visible;

                UpdatePlayerStatus(peer, " - connecting...");
                StreamSocket s = await PeerFinder.ConnectAsync(peer);

                ConnectedPeer temp = new ConnectedPeer(peer.DisplayName);
                connectedPeers[temp] = new SocketReaderWriter(s, this);
                connectedPeers[temp].ReadMessage();

                UpdatePlayerStatus(peer, " - ready");
                ConnectedPlayers.Items.Add(peer.DisplayName);

                startGameButton.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                sendInvitationsText.Text = "Cannot connect to " + peer.DisplayName;
            }

            // PeerFinder.ConnectAsync aborts PeerWatcher
            // restart PeerWatcher whether connect failed or succeeded
            StartPeerWatcher();
        }
        public async Task ConnectAndSendFileAsync(PeerInformation selectedPeer, StorageFile selectedFile)
        {
            var socket = await PeerFinder.ConnectAsync(selectedPeer);

            Verbose(string.Format("Connected to {0}, now processing transfer ...please wait", selectedPeer.DisplayName));
            await SendFileToPeerAsync(selectedPeer, socket, selectedFile);
        }
Example #10
0
            internal void Run()
            {
                PeerFinder.Role            = PeerRole.Client;
                PeerFinder.AllowWiFiDirect = true;
                PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged;

                if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                     Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                    Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
                {
                    Console.WriteLine("Peer discovery using Wi-Fi Direct is not supported.\n");
                    return;
                }

                PeerFinder.Start();

                var peerInfoCollection = PeerFinder.FindAllPeersAsync().AsTask().Result;

                if (peerInfoCollection.Count == 0)
                {
                    Console.WriteLine("No peers found");
                    return;
                }

                foreach (var info in peerInfoCollection)
                {
                    Console.WriteLine("Peer found: {0}", info.DisplayName);

                    Windows.Networking.Sockets.StreamSocket socket =
                        PeerFinder.ConnectAsync(info).AsTask().Result;

                    Sender(socket);
                }
            }
Example #11
0
        public async Task <StreamSocket> ConnectToDevice(PeerInformation peer)
        {
            return(await PeerFinder.ConnectAsync(peer));

            //Peer myPeer = peers.First(s => s.Name == identity);
            //return await PeerFinder.ConnectAsync(myPeer.Information);
        }
Example #12
0
        /// <summary>
        /// Connects to a phone or a device
        /// </summary>
        /// <param name="options"></param>
        public async void connect(string options)
        {
            ConnectionOptions connectionOptions;

            try
            {
                string[] args = JsonHelper.Deserialize <string[]>(options);
                connectionOptions = JsonHelper.Deserialize <ConnectionOptions>(args[0]);
            }
            catch (Exception)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            if (string.IsNullOrEmpty(connectionOptions.Address))
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                return;
            }

            try
            {
                PeerInformation peer = null;
                foreach (var discoveredDevice in discoveredPeers)
                {
                    //TODO It seems PeerInformation.HostName property sometimes returns null. So we connect to a phone/device by name instead of host address
                    if (discoveredDevice.DisplayName == connectionOptions.Address)
                    {
                        peer = discoveredDevice;
                    }
                }

                if (peer != null)
                {
                    if (connectionOptions.Type == ConnectionType.PhoneToPhone)
                    {
                        connectionSocket = await PeerFinder.ConnectAsync(peer);
                    }
                    else
                    {
                        //TODO this kind of connection has not been tested yet
                        connectionSocket = new StreamSocket();
                        await connectionSocket.ConnectAsync(peer.HostName, peer.ServiceName);
                    }

                    this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
                }
                else
                {
                    this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Unable to find a peer with the following address: " + connectionOptions.Address));
                }
            }
            catch (Exception)
            {
                this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while connecting to the peer"));
            }
        }
        public async Task <string> ReceiveFileAsync(PeerInformation requestingPeer, StorageFolder folder, string outputFilename = null)
        {
            Verbose("Connection in process...");
            StreamSocket socket = await PeerFinder.ConnectAsync(requestingPeer);

            Verbose("Receiving file...");

            return(await ReceiveFileFomPeer(socket, folder, outputFilename));
        }
Example #14
0
 /// <summary>
 /// Connects to incoming request.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private async void OnConnectionRequested(object sender, ConnectionRequestedEventArgs args)
 {
     try
     {
         connectionSocket = await PeerFinder.ConnectAsync(args.PeerInformation);
     }
     catch (Exception)
     {
         this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error occurred while processing incoming request"));
     }
 }
Example #15
0
        private async void PeerFinder_ConnectionRequested(object sender, ConnectionRequestedEventArgs args)
        {
            PeerInformation info = args.PeerInformation;

            socket = await PeerFinder.ConnectAsync(info);

            if (ConnectionReceived != null)
            {
                ConnectionReceived(this, new RfcommStreamSocketListenerConnectionReceivedEventArgs(socket));
            }
        }
Example #16
0
        public static async void ConnectToPeer(PeerInformation peer)
        {
            try {
                socket = await PeerFinder.ConnectAsync(peer);

                PeerFinder.Stop();
                ListenForIncomingCommand();
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
Example #17
0
        private async void DoConnect(Action <IConnectedSphero> onSuccess, Action <Exception> onError)
        {
            try
            {
                var spheroSocket = await PeerFinder.ConnectAsync(PeerInformation);

                onSuccess(new ConnectedSphero(PeerInformation, spheroSocket));
            }
            catch (Exception exception)
            {
                onError(exception);
            }
        }
Example #18
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;
                }
            }
        }
Example #19
0
            static void Receiver(PeerInformation peerInfo)
            {
                Console.WriteLine("Receiver waiting to connect async");

                Windows.Networking.Sockets.StreamSocket socket =
                    PeerFinder.ConnectAsync(peerInfo).AsTask().Result;

                Console.WriteLine("Receiver connection happened");

                int ini = Environment.TickCount;

                using (Stream streamRead = socket.InputStream.AsStreamForRead())
                    using (Stream streamWrite = socket.OutputStream.AsStreamForWrite())
                        using (BinaryReader reader = new BinaryReader(streamRead))
                            using (BinaryWriter writer = new BinaryWriter(streamWrite))
                            {
                                long totalToRead = reader.ReadInt64();

                                Console.WriteLine("Going to read {0} bytes", totalToRead);

                                long read = 0;

                                byte[] buffer = new byte[32 * 1024 * 1024];

                                while (read < totalToRead)
                                {
                                    long toRead = totalToRead - read;

                                    if (toRead >= buffer.Length)
                                    {
                                        toRead = buffer.Length;
                                    }

                                    reader.Read(buffer, 0, (int)toRead);

                                    Console.WriteLine("{0}/{1}", read, totalToRead);

                                    read += toRead;

                                    writer.Write(true);

                                    writer.Flush();
                                }

                                float MB   = totalToRead / 1024 / 1024;
                                float secs = (Environment.TickCount - ini) / 1000;

                                Console.WriteLine("Received {0} MB in {1} secs = {2:#0.##} MB/s",
                                                  MB, secs, MB / secs);
                            }
            }
Example #20
0
        /// <summary>
        /// 通过蓝牙连接设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btConnect_Click(object sender, RoutedEventArgs e)
        {
            Button          deleteButton = sender as Button;
            PeerInformation selectedPeer = deleteButton.DataContext as PeerInformation;

            //连接到选择的对等项
            socket = await PeerFinder.ConnectAsync(selectedPeer);

            //使用输出输入流建立数据读写对象
            dataReader = new DataReader(socket.InputStream);
            dataWriter = new DataWriter(socket.OutputStream);
            //开始读取消息
            PeerFinder_StartReader();
        }
Example #21
0
        /// <summary>
        /// Connect to detected remote device.
        ///
        /// Connecting action will be invoked when a socket connection is being created.
        /// Connected action will be invoked when a connection with another device has been established.
        /// ConnectivityProblem action will be invoked if connection to another device cannot be made.
        /// ConnectionInterrupted action will be invoked if connection to another device breaks.
        /// MessageReceived action will be invoked when a message from another device has been received.
        /// <param name="peer">Peer to connect to</param>
        /// </summary>
        public async void Connect(PeerInformation peer)
        {
            _status = ConnectionStatusValue.Connecting;

            try
            {
                if (Connecting != null)
                {
                    Connecting();
                }

                _socket = await PeerFinder.ConnectAsync(peer);

                if (_socket != null)
                {
                    PeerFinder.TriggeredConnectionStateChanged -= TriggeredConnectionStateChanged;
                    PeerFinder.ConnectionRequested             -= ConnectionRequested;

                    _status = ConnectionStatusValue.Connected;

                    _writer = new DataWriter(_socket.OutputStream);
                    _writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    _writer.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    _reader = new DataReader(_socket.InputStream);
                    _reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    _reader.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    ListenAsync();

                    SendNameAsync(NFCTalk.DataContext.Singleton.Settings.Name);

                    if (Connected != null)
                    {
                        Connected();
                    }
                }
                else if (ConnectivityProblem != null)
                {
                    ConnectivityProblem();
                }
            }
            catch (Exception ex)
            {
                if (ConnectivityProblem != null)
                {
                    ConnectivityProblem();
                }
            }
        }
        async private void PeerFinder_Accept(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("Connecting to " + _requestingPeer.DisplayName + "....", NotifyType.StatusMessage);
            PeerFinder_AcceptButton.Visibility = Visibility.Collapsed;
            try
            {
                StreamSocket socket = await PeerFinder.ConnectAsync(_requestingPeer);

                rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage);
                PeerFinder_StartSendReceive(socket);
            }
            catch (Exception err)
            {
                rootPage.NotifyUser("Connection to " + _requestingPeer.DisplayName + " failed: " + err.Message, NotifyType.ErrorMessage);
            }
        }
Example #23
0
        private async void ReceiveImage(PeerInformation peer)
        {
            try
            {
                Status.Text = "Verbinde mit Peer...";
                StreamSocket peerSocket = await PeerFinder.ConnectAsync(peer);

                Status.Text = "Verbunden. Empfange Daten...";

                // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
                var reader = new DataReader(peerSocket.InputStream);

                // Anzahl der Bytes abrufen, aus denen das Bild besteht
                // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
                await reader.LoadAsync(4);

                int imageSize = reader.ReadInt32();

                // Bytearray des Bildes laden
                await reader.LoadAsync((uint)imageSize);

                byte[] imageBytes = new byte[imageSize];
                reader.ReadBytes(imageBytes);

                // Bytearray in Stream laden und anzeigen
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
                Status.Text = "Bild empfangen.";

                // Ressourcen freigeben
                reader.Dispose();
                peerSocket.Dispose();

                // Wieder Verbindungen akzeptieren
                PeerFinder.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
Example #24
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);
            }
        }
Example #25
0
        private async Task ConnectCommand()
        {
            this.IsConnecting = true;

            try
            {
                this.ConnectedPeer = "Connecting...";
                var socket = await PeerFinder.ConnectAsync(this.SelectedPeer.Information);

                this.InitializeSocket(socket);
                this.ConnectedPeer = this.SelectedPeer.Name;
            }
            catch (Exception ex)
            {
                this.ErrorMessage  = ex.Message;
                this.ConnectedPeer = "Connection Failed.";
            }

            this.IsConnecting = false;
        }
Example #26
0
        private async void PeerFinderConnectionRequested(object sender, ConnectionRequestedEventArgs args)
        {
            if (this.isConnecting)
            {
                return;
            }

            try
            {
                this.RouteToUiThread(
                    () =>
                {
                    this.IsConnecting  = true;
                    this.ConnectedPeer = string.Format(
                        "Incoming request from {0}...",
                        args.PeerInformation.DisplayName);
                });

                var socket = await PeerFinder.ConnectAsync(args.PeerInformation);

                this.InitializeSocket(socket);
                this.RouteToUiThread(
                    () =>
                {
                    this.IsConnecting = false;
                    var peer          =
                        this.Peers.FirstOrDefault(p => p.Information.Id == args.PeerInformation.Id);
                    if (peer == null)
                    {
                        peer = new FoundPeer(args.PeerInformation);
                        this.Peers.Add(peer);
                    }
                    this.SelectedPeer  = peer;
                    this.ConnectedPeer = peer.Name;
                });
            }
            catch (Exception ex)
            {
                this.RouteToUiThread(() => this.ErrorMessage = ex.Message);
            }
        }
Example #27
0
        async void ConnectToPeer(PeerInformation peer)
        {
            try
            {
                StreamSocket socket = await PeerFinder.ConnectAsync(peer);

                App.Socket = socket;


                //imageBytes = await dataHelper.ReceiveDataAsync();

                //this.Dispatcher.BeginInvoke(() =>
                //{
                //    MessageBox.Show(string.Format("Received {0} bytes", imageBytes.Length));
                //});
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #28
0
    public async Task <bool> ConnectToPeer(PeerInformation peer)
    {
        try {
            _socket = await PeerFinder.ConnectAsync(peer);

            if (_socket != null)
            {
                // Den PeerFinder stoppen, um Energie zu sparen ;-)
                PeerFinder.Stop();
                _peerName   = peer.DisplayName;
                _dataReader = new DataReader(_socket.InputStream);
                _dataWriter = new DataWriter(_socket.OutputStream);
                _dataReadWorker.RunWorkerAsync();
                return(true);
            }
        } catch (Exception ex) {
            MessageBox.Show(ex.Message);
            Terminate();
        }
        return(false);
    }
Example #29
0
        private async void TransferPicture_Click(object sender, RoutedEventArgs e)
        {
            var selectedPeer = PeersList.SelectedItem as PeerInformation;

            if (selectedPeer == null)
            {
                MessageBox.Show("Bitte Emfängergerät wählen");
                return;
            }

            try
            {
                Status.Text = "Verbinde mit Peer...";
                var peerSocket = await PeerFinder.ConnectAsync(selectedPeer);

                var writer = new DataWriter(peerSocket.OutputStream);

                Status.Text = "Verbunden. Übertrage Bild...";

                // Anzahl der zu übertragenden Bytes übertragen
                writer.WriteInt32(App.ImageBytesToTransfer.Length);
                await writer.StoreAsync();

                // Image-Bytes übertragen
                writer.WriteBytes(App.ImageBytesToTransfer);
                await writer.StoreAsync();

                await writer.FlushAsync();

                // Ressourcen freigeben
                writer.Dispose();
                peerSocket.Dispose();
                Status.Text = "Übertragung abgeschlossen";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
        private void DoConnect(PeerInformation peerInformation)
        {
#if WINDOWS_PHONE
            if (peerInformation.HostName != null)
            {
                DoConnect(peerInformation.HostName, peerInformation.ServiceName);
                return;
            }
#endif

            PeerFinder.ConnectAsync(peerInformation).AsTask().ContinueWith(p =>
            {
                if (!p.IsFaulted)
                {
                    DoConnect(p.Result);
                }
                else
                {
                    Debug.WriteLine("connection fault");
                    FireConnectionStatusChanged(TriggeredConnectState.Failed);
                }
            });
        }