Exemplo n.º 1
0
        public async Task Connect(HostName serverHost, string serverPort)
        {
            await socket.ConnectAsync(serverHost, serverPort);

            //Send identifier
            //TODO: should be a json containing some connection identifiers
            IBuffer buffUTF8 = CryptographicBuffer.ConvertStringToBinary("Receiver", BinaryStringEncoding.Utf8);
            //TODO await token??
            await socket.OutputStream.WriteAsync(buffUTF8);

            Debug.WriteLine("Socket address: " + socket.Information.RemoteAddress + " And " + socket.Information.LocalAddress);
        }
Exemplo n.º 2
0
        public async Task ConnectAsync()
        {
            this.socket = new StreamSocket();
            await socket.ConnectAsync(
                device.ConnectionHostName,
                device.ConnectionServiceName);

            this.dataReader = new DataReader(socket.InputStream);
            this.dataReader.InputStreamOptions = InputStreamOptions.Partial;

            this.dataWriter = new DataWriter(socket.OutputStream);
        }
Exemplo n.º 3
0
        private async void InitializeRfcommServer()
        {
            try
            {
                listBoxDevices.Text = string.Empty;
                string device1 = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
                deviceCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(device1);

                selectedDevice = deviceCollection[0];
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                    foreach (var item in deviceCollection)
                    {
                        listBoxDevices.Text += "\n========================";
                        listBoxDevices.Text += "\nDevice";
                        listBoxDevices.Text += string.Format("\nName: {0}\nId: {1}", item.Name, item.Id);
                        listBoxDevices.Text += "\n========================";
                        listBoxDevices.Text += "\nProperties";
                        listBoxDevices.Text += "\n========================";
                        foreach (var prop in item.Properties)
                        {
                            listBoxDevices.Text += string.Format("\nName: {0} - \tValue: {1}", prop.Key, prop.Value);
                        }
                        listBoxDevices.Text += "\n========================";
                    }
                });

                deviceService = await RfcommDeviceService.FromIdAsync(selectedDevice.Id);

                if (deviceService != null)
                {
                    //connect the socket
                    try
                    {
                        await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName);
                    }
                    catch (Exception ex)
                    {
                        errorStatus.Visibility = Visibility.Visible;
                        errorStatus.Text       = "Cannot connect bluetooth device:" + ex.Message;
                    }
                }
                else
                {
                    errorStatus.Visibility = Visibility.Visible;
                    errorStatus.Text       = "Didn't find the specified bluetooth device";
                }
            }
            catch (Exception exception)
            {
                errorStatus.Visibility = Visibility.Visible;
                errorStatus.Text       = exception.Message;
            }
        }
        async private void MyCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MyRing.IsActive = true;
            MyText.Text     = "正在连接,请稍后";
            var combo = (ComboBox)sender;
            var a     = combo.SelectedItem as PairedDeviceInfo;

            Parallel.Invoke();
            bool success = true;

            try
            {
                _service = await RfcommDeviceService.FromIdAsync(a.ID);

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try
                {
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);
                }
                catch (Exception ex)
                {
                    success = false;
                    System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    this.buttonDisconnect.IsEnabled = true;
                    this.buttonSend.IsEnabled       = true;
                    this.buttonStartRecv.IsEnabled  = true;
                    this.buttonStopRecv.IsEnabled   = false;
                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    //MessageDialog md = new MessageDialog(msg, Title);
                    System.Diagnostics.Debug.WriteLine(msg);
                    //await md.ShowAsync();
                    MyRing.IsActive = false;
                    MyText.Text     = "连接成功";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
                _socket.Dispose();
                _socket = null;
            }
        }
Exemplo n.º 5
0
        public async Task SendMessage(IPAddress endpoint, T content)
        {
            using (var socket = new StreamSocket())
            {
                await socket.ConnectAsync(new HostName(endpoint.ToString()), LocalPort.ToString());

                var writer = new DataWriter(socket.OutputStream);
                await _formatter.Write(writer, content);

                await writer.StoreAsync();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Connect to the given host device.
        /// </summary>
        /// <param name="deviceHostName">The host device name.</param>
        public async void Connect(HostName deviceHostName)
        {
            if (socket != null)
            {
                await socket.ConnectAsync(deviceHostName, "1");

                dataWriter = new DataWriter(socket.OutputStream);
                dataReader = new DataReader(socket.InputStream);
                dataReadWorker.RunWorkerAsync();
                Debug.WriteLine(dataWriter != null);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Internal function for setup TLS connection
        /// </summary>
        /// <param name="socket">Connection socket</param>
        /// <param name="hostName">Host name</param>
        /// <param name="port">Port number</param>
        /// <returns>False if the connection should be repeated</returns>
        private async Task <bool> TryConnectSocketWithRetryAsync(StreamSocket socket, HostName hostName, string port)
        {
            try
            {
                // Establish a secure connection to the server (by default, the local IIS server).
                await socket.ConnectAsync(hostName, port, SocketProtectionLevel.Tls12);

                string certInformation = GetCertificateInformation(
                    socket.Information.ServerCertificate,
                    socket.Information.ServerIntermediateCertificates);

                return(false);
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.HostNotFound)
                {
                    return(true);
                }

                // If the exception was caused by an SSL error that is ignorable we are going to prompt the user
                // with an enumeration of the errors and ask for permission to ignore.
                if (socket.Information.ServerCertificateErrorSeverity != SocketSslErrorSeverity.Ignorable)
                {
                    return(true);
                }
            }

            // Present the certificate issues and ask the user if we should continue.
            if (await ShouldIgnoreCertificateErrorsAsync(socket.Information.ServerCertificateErrors))
            {
                // -----------------------------------------------------------------------------------------------
                // WARNING: Only test applications should ignore SSL errors.
                // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle attacks.
                // -----------------------------------------------------------------------------------------------
                socket.Control.IgnorableServerCertificateErrors.Clear();
                foreach (var ignorableError in socket.Information.ServerCertificateErrors)
                {
                    socket.Control.IgnorableServerCertificateErrors.Add(ignorableError);
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Connect to the ELIServer.
        /// After the connetion is made, a message with the ClientID and ID of the user is send.
        /// </summary>
        /// <returns>A Task that can be awaited.</returns>
        private async Task Connect()
        {
            await socket.ConnectAsync(serverHost, serverPort);

            isConnected = true;
            JsonObject json = new JsonObject();

            json.Add("ClientID", JsonValue.CreateStringValue("1"));
            json.Add("ID", JsonValue.CreateStringValue("1"));
            json.Add("TYPE", JsonValue.CreateStringValue("Connect"));
            await SendMessage(json);
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Initializes a thread and starts pinging the specified server
        ///     Calculates the ping and delta of each ping in ms
        /// </summary>
        public void StartPing(int numberOfPings)
        {
            _isRunning = true;
            _totalTime = 0;

            IAsyncAction _pingAction = ThreadPool.RunAsync(async workItem => {
                var previousPingTime = 0;
                var delta            = 0;
                var pingIteration    = 1;
                while (pingIteration <= numberOfPings && _isRunning)
                {
                    var stopwatch = new Stopwatch();
                    var socket    = new StreamSocket();
                    stopwatch.Start();
                    try
                    {
                        await socket.ConnectAsync(new HostName(_url), "80");
                    } catch (Exception e)
                    {
                        OnThreadFinished(FinishType.ERROR);
                        OnThreadFinished(FinishType.FINISHED);
                        return;
                    }

                    stopwatch.Stop();

                    var ms = (int)stopwatch.ElapsedMilliseconds;

                    // First time there is no delta
                    if (pingIteration > 0)
                    {
                        delta            = Math.Abs(ms - previousPingTime);
                        previousPingTime = ms;
                    }

                    Interlocked.Add(ref _totalTime, ms + delta);

                    HorseProgressEventArgs horseProgressEventArgs = new HorseProgressEventArgs(_totalTime, pingIteration);
                    OnPingReceived(horseProgressEventArgs);

                    Thread.Sleep(1000);
                    pingIteration++;
                }

                if (!_isRunning)
                {
                    OnThreadFinished(FinishType.CANCELED);
                    return;
                }

                OnThreadFinished(FinishType.FINISHED);
            });
        }
Exemplo n.º 10
0
        public async Task StartFresh()
        {
            Log("Starting fresh");
            if (!InternetAvailable())
            {
                Log("Internet not available. Exiting.");
                return;
            }

            if (Running)
            {
                Log("realtime client is already running");
                return;
            }

            if (AppIsInBackground)
            {
                Log("Application is in background");
                return;
            }
            if (Socket != null)
            {
                Shutdown();
                await Task.Delay(350);
            }
            try
            {
                var connectPacket = new FbnsConnectPacket
                {
                    Payload = await RealtimePayload.BuildPayload(_instaApi)
                };
                Socket = new StreamSocket();
                Socket.Control.KeepAlive = true;
                Socket.Control.NoDelay   = true;
                Socket.Control.OutboundBufferSizeInBytes = 20 * 1024 * 1024;
                await Socket.ConnectAsync(new HostName(DEFAULT_HOST), "443", SocketProtectionLevel.Tls12);

                _inboundReader                    = new DataReader(Socket.InputStream);
                _outboundWriter                   = new DataWriter(Socket.OutputStream);
                _inboundReader.ByteOrder          = ByteOrder.BigEndian;
                _inboundReader.InputStreamOptions = InputStreamOptions.Partial;
                _outboundWriter.ByteOrder         = ByteOrder.BigEndian;
                _runningTokenSource               = new CancellationTokenSource();
                await FbnsPacketEncoder.EncodePacket(connectPacket, _outboundWriter);
            }
            catch (Exception e)
            {
                e.PrintInDebug();
                Restart();
                return;
            }
            StartPollingLoop();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Connects to the specified <see cref="RfcommDeviceService"/> and returns a <see cref="Stream"/> of the encrypted connection.
        /// </summary>
        /// <param name="device">The device to connect to.</param>
        /// <returns>The connection stream.</returns>
        public static dynamic Connect(RfcommDeviceService device)
        {
            Log.RecordEvent(typeof(BluetoothUtils), $"Attempting to connect to {device.ConnectionHostName.CanonicalName} via Bluetooth RFCOMM.", LogEntrySeverity.Info);
            var socket = new StreamSocket();

            new Func <Task>(async() =>
            {
                await socket.ConnectAsync(device.ConnectionHostName, RfcommConnectionService.AsString(), SocketProtectionLevel.BluetoothEncryptionWithAuthentication);
            })().Wait();
            Log.RecordEvent(typeof(BluetoothUtils), $"Connection to {device.ConnectionHostName.CanonicalName} via Bluetooth RFCOMM was successful.", LogEntrySeverity.Info);
            return(new SplitStream(socket.InputStream.AsStreamForRead(), socket.OutputStream.AsStreamForWrite()));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates the protocol - encapsulates the socket creation
        /// </summary>
        /// <param name="peer">The peer.</param>
        /// <returns>A protocol object</returns>
        public static async Task<Protocol> CreateProtocolAsync(PeerInformation peer)
        {
#if WINDOWS_PHONE || WINDOWS_PHONE_APP
            // {00001101-0000-1000-8000-00805f9b34fb} specifies we want a Serial Port - see http://developer.nokia.com/Community/Wiki/Bluetooth_Services_for_Windows_Phone
            // {00000000-deca-fade-deca-deafdecacaff} Fix ServiceID for WP8.1 Update 2
            StreamSocket socket = new StreamSocket();
            await socket.ConnectAsync(peer.HostName, Guid.Parse("00000000-deca-fade-deca-deafdecacaff").ToString("B"));
            return new Protocol(socket);
#endif

            throw new NotImplementedException();
        }
        public async Task OpenAsync(string hostName, int port, bool useSsl)
        {
            if (_socket == null)
            {
                _socket = new StreamSocket( );

                if (useSsl)
                {
                    await _socket.ConnectAsync(new HostName( hostName ), port.ToString( ), SocketProtectionLevel.Tls10);
                }
                else
                {
                    await _socket.ConnectAsync(new HostName( hostName ), port.ToString( ));
                }

                _reader = new DataReader(_socket.InputStream);
                _reader.InputStreamOptions = InputStreamOptions.Partial;

                _writer = new DataWriter(_socket.OutputStream);
            }
        }
Exemplo n.º 14
0
        async private static void ConnectDevice()
        {
            //Revision: No need to requery for Device Information as we alraedy have it:
            DeviceInformation DeviceInfo; // = await DeviceInformation.CreateFromIdAsync(this.TxtBlock_SelectedID.Text);
            PairedDeviceInfo  pairedDevice = _pairedDevices[0];

            DeviceInfo = pairedDevice.DeviceInfo;
            try
            {
                while (_service == null)
                {
                    _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);
                }

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try
                {
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);

                    success = true;
                    MainPage.SendReceiveStart();
                }
                catch (Exception ex)
                {
                    success = false;
                    ConnectDevice();
                    System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    //MessageDialog md = new MessageDialog(msg, Title);
                    System.Diagnostics.Debug.WriteLine(msg);
                    Listen();
                    //await md.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
                _socket.Dispose();
                _socket = null;
            }
        }
Exemplo n.º 15
0
    private async void TCPclient()
    {
        Debug.Log("Initializing TCP Client...");
        try
        {
            _socket = new StreamSocket();
            Debug.Log("Connecting to " + Host + ":" + Port);
            HostName serverHost = new HostName(Host);

            await _socket.ConnectAsync(serverHost, Port);

            //Connection Suscess
            Debug.Log("Connected");
            AppManager.NextState();
            _connection = true;
            //Write data to the echo server.

            /*
             * Stream streamOut = _socket.OutputStream.AsStreamForWrite();
             * StreamWriter writer = new StreamWriter(streamOut);
             * string request = "";
             * await writer.WriteLineAsync(request);
             * await writer.FlushAsync();
             */
            //Read data from the server.
            Stream       streamIn = _socket.InputStream.AsStreamForRead();
            StreamReader reader   = new StreamReader(streamIn);
            await reader.ReadLineAsync();

            while (_connection == true)
            {
                try
                {
                    string response = await reader.ReadLineAsync();

                    Debug.Log("Revieced: " + response);
                    _pianodriver.RecievePianoData(response);
                }
                catch (Exception e)
                {
                    Debug.Log("Connection error! :" + e.ToString());
                }
            }
        }
        catch (Exception e)
        {
            //Handle exception here.
            Debug.Log("Connection error! :" + e.ToString());
            AppManager.ChangeState(StageManager.State.QRScan);
            Destroy(this.transform.parent);
        }
    }
Exemplo n.º 16
0
        public async Task SendAttachment(User rec, StorageFile fileToSend, List <User> groupMessageUsers = null)
        {
            StreamSocket fileTransferSocket = new StreamSocket();
            await fileTransferSocket.ConnectAsync(new HostName(rec.IPAddress), fileTransferServicePort);


            byte[] buff = new byte[1024];
            var    prop = await fileToSend.GetBasicPropertiesAsync();

            using (var dataOutputStream = new DataWriter(fileTransferSocket.OutputStream))
            {
                if (groupMessageUsers != null)
                {
                    string usrs = "";
                    usrs += "group;";
                    usrs += ChatScreen.loggedInUser.Username + ";";
                    foreach (User u in groupMessageUsers)
                    {
                        usrs += u.Username;
                        if (u != groupMessageUsers.Last())
                        {
                            usrs += ";";
                        }
                    }
                    dataOutputStream.WriteInt32(usrs.Length);
                    dataOutputStream.WriteString(usrs);
                }
                else
                {
                    dataOutputStream.WriteInt32(ChatScreen.loggedInUser.Username.Length);
                    dataOutputStream.WriteString(ChatScreen.loggedInUser.Username);
                }

                dataOutputStream.WriteInt32(fileToSend.Name.Length);
                dataOutputStream.WriteString(fileToSend.Name);
                dataOutputStream.WriteUInt64(prop.Size);
                var fileStream = await fileToSend.OpenStreamForReadAsync();

                while (fileStream.Position < (long)prop.Size)
                {
                    var rlen = await fileStream.ReadAsync(buff, 0, buff.Length);

                    dataOutputStream.WriteBytes(buff);
                }
                await dataOutputStream.FlushAsync();

                await dataOutputStream.StoreAsync();

                await fileTransferSocket.OutputStream.FlushAsync();
            }
            fileTransferSocket.Dispose();
        }
Exemplo n.º 17
0
        /// <summary>
        /// 连接服务器
        /// </summary>
        public static async Task <bool> ConnectServer()
        {
            if (hasConnected)
            {
                return(true);
            }
            clientSocket = new StreamSocket();
            clientSocket.Control.KeepAlive = true;
            await clientSocket.ConnectAsync(new HostName("HCHAO"), "10920");

            hasConnected = true;
            return(true);
        }
Exemplo n.º 18
0
        public async void Connect(string ip)
        {
            TCPSocket = new StreamSocket();
            gameBrain.Debug("trying to TCP connect " + new Windows.Networking.HostName(ip).CanonicalName + ":" + Utils.devicesTCPPort.ToString());
            await TCPSocket.ConnectAsync(new Windows.Networking.HostName(ip), Utils.devicesTCPPort.ToString());

            TCPWriter = new DataWriter(TCPSocket.OutputStream);
            TCPReader = new DataReader(TCPSocket.InputStream);


            StartListening();
            Send("message From gameBrain: welcoma aboard");
        }
Exemplo n.º 19
0
        public async Task ConnectAsync(CancellationToken cancellationToken)
        {
            if (_socket == null)
            {
                _socket = new StreamSocket();
                _socket.Control.NoDelay   = _options.NoDelay;
                _socket.Control.KeepAlive = true;
            }

            if (_options.TlsOptions?.UseTls != true)
            {
                await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString());
            }
            else
            {
                _socket.Control.ClientCertificate = LoadCertificate(_options);

                foreach (var ignorableChainValidationResult in ResolveIgnorableServerCertificateErrors())
                {
                    _socket.Control.IgnorableServerCertificateErrors.Add(ignorableChainValidationResult);
                }

                var socketProtectionLevel = SocketProtectionLevel.Tls12;
                if (_options.TlsOptions.SslProtocol == SslProtocols.Tls11)
                {
                    socketProtectionLevel = SocketProtectionLevel.Tls11;
                }
                else if (_options.TlsOptions.SslProtocol == SslProtocols.Tls)
                {
                    socketProtectionLevel = SocketProtectionLevel.Tls10;
                }

                await _socket.ConnectAsync(new HostName(_options.Server), _options.GetPort().ToString(), socketProtectionLevel);
            }

            Endpoint = _socket.Information.RemoteAddress + ":" + _socket.Information.RemotePort;

            CreateStreams();
        }
Exemplo n.º 20
0
        private async Task <bool> ConnectClient(HostName address, string port, StreamSocket client)
        {
            try
            {
                await client.ConnectAsync(address, port);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Connect to socket server and start listening
        /// </summary>
        public async void Connect()
        {
            logOutFlag = false;
            socket     = new StreamSocket();
            await socket.ConnectAsync(new HostName(Hostname), Port);

#pragma warning disable CS4014 // Need await
            Task.Factory.StartNew(() => ListenForData());
#pragma warning restore CS4014 // Need await
            await Login();

            heartTimer = new Timer(SendHeart, null, 30 * 1000, 30 * 1000);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Connect operation. Will return true if successful
        /// </summary>
        public async Task <bool> Connect()
        {
            _Socket = new StreamSocket();
            _Socket.Control.OutboundBufferSizeInBytes = _OutboundBufferSize;

            await _Socket.ConnectAsync(_CameraHost, _port.ToString());

            // add after calling ConnectAsync on the StreamSocket Object
            _reader = new DataReader(_Socket.InputStream);
            _writer = new DataWriter(_Socket.OutputStream);

            return(true);
        }
Exemplo n.º 23
0
        private async void StartReceiving_Click(object sender, RoutedEventArgs e)
        {
            Status.Text = "Verbinde mit Server...";

            // Socket erzeugen und mit Server anhand der IP verbinden
            var socket = new StreamSocket();
            await socket.ConnectAsync(new HostName(IpAddress.Text), Port);

            Status.Text = "Mit Server verbunen. Empfange Bild...";

            // Bild empfangen
            ReceiveImage(socket);
        }
Exemplo n.º 24
0
        async Task <StreamWrapper> IConnectionFactory.Connect(string hostname, int port, bool useSsl)
        {
            var socket = new StreamSocket();

            socket.Control.KeepAlive = true;
            socket.Control.NoDelay   = true;
            await socket.ConnectAsync(new HostName (hostname), port.ToString(), useSsl?SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket);

            return(new StreamWrapper()
            {
                OutputStream = socket.OutputStream.AsStreamForWrite(), InputStream = socket.InputStream.AsStreamForRead()
            });
        }
Exemplo n.º 25
0
        public async Task Connect(DeviceInformation device)
        {
            RfcommDeviceService service = null;
            StreamSocket        socket  = null;
            BinaryWriter        writer  = null;

            Disconnect();

            try
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    try
                    {
                        service = await RfcommDeviceService.FromIdAsync(device.Id);
                    }
                    catch (Exception e)
                    {
                        await new Windows.UI.Popups.MessageDialog(e.Message).ShowAsync();
                    }
                });

                if (service == null)
                {
                    await new Windows.UI.Popups.MessageDialog("No Service found").ShowAsync();
                    return;
                }

                socket = new StreamSocket();

                await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName,
                                          SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                writer = new BinaryWriter(socket.OutputStream.AsStreamForWrite());

                Service = service;
                Socket  = socket;
                Writer  = writer;
                Device  = device;
            }
            catch (Exception e)
            {
                writer?.Dispose();
                writer = null;

                socket?.Dispose();
                socket = null;

                throw;
            }
        }
Exemplo n.º 26
0
        public async Task SendCommand(string command)
        {
            if ((_Host != null) && (_PortNumber != null))
            {
                ShowMessage("Connecting to " + _Host + ":" + _PortNumber);

                streamSocket = new Windows.Networking.Sockets.StreamSocket();

                try
                {
                    var hostName = new Windows.Networking.HostName(_Host);

                    await streamSocket.ConnectAsync(hostName, _PortNumber);

                    ShowMessage("Connected!");

                    using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
                    {
                        using (var streamWriter = new StreamWriter(outputStream))
                        {
                            await streamWriter.WriteLineAsync(command);

                            await streamWriter.FlushAsync();

                            ShowMessage("Sent!");
                        }
                    }

                    // Read data from the echo server.
                    string response;
                    using (Stream inputStream = streamSocket.InputStream.AsStreamForRead())
                    {
                        using (StreamReader streamReader = new StreamReader(inputStream))
                        {
                            if (!streamReader.EndOfStream)
                            {
                                response = await streamReader.ReadLineAsync();

                                ShowMessage(response);
                            }
                        }
                    }

                    streamSocket.Dispose();
                }
                catch (Exception E)
                {
                    ShowMessage(E.Message);
                }
            }
        }
Exemplo n.º 27
0
        async private void ConnectDevice_Click(object sender, RoutedEventArgs e)
        {
            //Revision: No need to requery for Device Information as we alraedy have it:
            DeviceInformation DeviceInfo; // = await DeviceInformation.CreateFromIdAsync(this.TxtBlock_SelectedID.Text);
            PairedDeviceInfo  pairedDevice = (PairedDeviceInfo)ConnectDevices.SelectedItem;

            DeviceInfo = pairedDevice.DeviceInfo;

            bool success = true;

            try
            {
                _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try
                {
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);
                }
                catch (Exception ex)
                {
                    success = false;
                    System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    this.buttonDisconnect.IsEnabled = true;
                    this.buttonSend.IsEnabled       = true;
                    this.buttonStartRecv.IsEnabled  = true;
                    this.buttonStopRecv.IsEnabled   = false;
                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    //MessageDialog md = new MessageDialog(msg, Title);
                    System.Diagnostics.Debug.WriteLine(msg);
                    //await md.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
                _socket.Dispose();
                _socket = null;
            }
        }
Exemplo n.º 28
0
        public async Task ConnectAsync()
        {
            IsConnected = false;
            _socket     = new StreamSocket();
            await _socket.ConnectAsync(new HostName(GlobalConfig.IpAddress), GlobalConfig.Port.ToString());

            IsConnected = true;
            _dataWriter = new DataWriter(_socket.OutputStream);
            _dataReader = new DataReader(_socket.InputStream)
            {
                InputStreamOptions = InputStreamOptions.Partial
            };
            StartListening();
        }
Exemplo n.º 29
0
        public async Task ConnectAsync(string ipAddress, int port)
        {
            _cancelListenerSource = new CancellationTokenSource();

            _socket = new Windows.Networking.Sockets.StreamSocket();
            var host = new Windows.Networking.HostName(ipAddress);
            await _socket.ConnectAsync(host, port.ToString());

            _inputStream = _socket.InputStream.AsStreamForRead();
            _reader      = new StreamReader(_inputStream);

            _outputStream = _socket.OutputStream.AsStreamForWrite();
            _writer       = new StreamWriter(_outputStream);
        }
Exemplo n.º 30
0
        public async Task ConnectAsync(Address address, ConnectionFactory factory)
        {
            SocketProtectionLevel spl = !address.UseSsl ?
                                        SocketProtectionLevel.PlainSocket :
#if NETFX_CORE
                                        SocketProtectionLevel.Tls12;
#else
                                        SocketProtectionLevel.Ssl;
#endif
            StreamSocket ss = new StreamSocket();
            await ss.ConnectAsync(new HostName(address.Host), address.Port.ToString(), spl);

            this.socket = ss;
        }