Exemplo n.º 1
0
        private void ConnectToServer()
        {
            TcpClient client = new TcpClient();

            IPAddress ServiceIP = IPAddress.Parse(Form1.serviceIP);

            try
            {
                Console.WriteLine("Connecting...");
                var result = client.BeginConnect(ServiceIP, 1738, null, client);
                //client.Connect(ServiceIP, 1738);
                Console.WriteLine("Connected!");

                if (result.AsyncWaitHandle.WaitOne(2000))
                {
                    while (client.Connected)
                    {
                        NetworkStream   ns = client.GetStream();
                        BinaryFormatter bf = new BinaryFormatter();

                        Image backgroundImg = Image.FromFile(filePath.Text);

                        byte[] action   = Encoding.ASCII.GetBytes("img\n");
                        byte[] image    = ImageToByteArray(backgroundImg);
                        byte[] combined = action.Concat(image).ToArray();

                        bf.Serialize(ns, combined);

                        client.Close();
                    }
                }
            }
            catch (Exception e)
            {
                client.Close();
                Console.WriteLine(e.ToString());
                return;
            }
            client.Close();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                _UseKeepalives = args.Any(a => a.Equals("--keepalive"));
            }

            _Client = new TcpClient();
            _Token  = _TokenSource.Token;

            if (_UseKeepalives)
            {
                Console.WriteLine("Enabling TCP keepalives");
                SetTcpKeepalives();
            }
            else
            {
                Console.WriteLine("TCP keepalives disabled");
            }

            IAsyncResult ar = _Client.BeginConnect("127.0.0.1", 9000, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
            {
                _Client.Close();
                throw new TimeoutException();
            }

            _Client.EndConnect(ar);
            _NetworkStream = _Client.GetStream();

            Task.Run(() => DataReceiver(), _Token);

            Console.WriteLine("Connected to tcp://127.0.0.1:9000, ENTER to exit");
            Console.ReadLine();
            _TokenSource.Cancel();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Username? ");
            username = Console.ReadLine();
            Console.WriteLine("Password? ");
            password = Console.ReadLine();

            client = new TcpClient();
            client.BeginConnect("localhost", 15243, new AsyncCallback(OnConnect), null);

            while (true)
            {
                if (connected)
                {
                    Console.WriteLine("Chat:");
                    string newChatMessage = Console.ReadLine();
                    write($"{username}:{newChatMessage}");
                }
                else
                {
                    Console.WriteLine("Connecting...");
                }
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome user!");
            Console.WriteLine("Whats your name? ");
            Username = Console.ReadLine();
            //username = "******";

            VrController = new VRController();
            IBike bike;

            if (UseRealBike)
            {
                InitBLEConnection();
                bike           = new RealBike(BleBike, BleHeart);
                LastResistance = 0;
                LastSpeed      = -1;
                LastHeartRate  = -1;
            }
            else
            {
                Data           = new BikeData(5, 120, 30, 5);
                LastSpeed      = 5;
                LastHeartRate  = 120;
                LastResistance = 30;
                bike           = new SimBike(Data);
            }
            bike.OnSpeed     += Bike_OnSpeed;
            bike.OnHeartRate += Bike_OnHeartrate;
            bike.OnSend      += Bike_OnSend;

            Client = new TcpClient();
            Client.BeginConnect("localhost", 15243, new AsyncCallback(OnConnect), null);

            while (true)
            {
                if (RunningTraining)
                {
                    if (!UseRealBike)
                    {
                        if (Console.ReadLine() == "")
                        {
                            Console.WriteLine("Input Command(Speed/HeartRate): ");
                            string command = Console.ReadLine();
                            switch (command)
                            {
                            case "Speed":
                                Console.WriteLine("Input Speed: ");
                                float speed = float.Parse(Console.ReadLine());
                                Console.WriteLine(speed.ToString());
                                Data.Speed = speed;
                                break;

                            case "HeartRate":
                                Console.WriteLine("Input HeartRAte: ");
                                int heartRate = int.Parse(Console.ReadLine());
                                Data.HeartRate = heartRate;
                                break;

                            default:
                                Console.WriteLine($"{command} is not a valid input!");
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        void ConnectThread(object _maxRetryCount)
        {
            int maxRetryCount = _maxRetryCount as int? ?? 0;
            int waitTime      = 500;

            netClient = new TcpClient();
            for (int i = 0; i <= maxRetryCount; ++i, waitTime *= 2)
            {
                try
                {
                    netClient = new TcpClient();
                    var asyncResult = netClient.BeginConnect(hostname, port, null, null);

                    try
                    {
                        // Stop what we're doing if the connection is cancelled from the main thread
                        if (EventWaitHandle.WaitAny(new WaitHandle[] { connectDone, asyncResult.AsyncWaitHandle }) == 0)
                        {
                            netClient.Close();
                            netClient = null;

                            return;
                        }

                        netClient.EndConnect(asyncResult);
                    }
                    finally
                    {
                        asyncResult.AsyncWaitHandle.Close();
                    }

                    break;
                }
                catch (SocketException ex)
                {
                    if (i == maxRetryCount)
                    {
                        NotifyConnectionResult(false, ex.Message);
                        return;
                    }
                    else
                    {
                        Thread.Sleep(waitTime);
                    }
                }
            }

            // If the main thread cancels the connection, this will be set to true
            bool itsOver = false;

            client.Connect(netClient.GetStream());
            client.LogIn(username, password, (sender, e) =>
            {
                if (itsOver)
                {
                    return;
                }

                NotifyConnectionResult(e.Success, e.ResultMessage);

                connectDone.Set();
            });

            connectDone.WaitOne();
            itsOver = true;
        }
Exemplo n.º 6
0
 public Client(string adress, int port)
 {
     this.client    = new TcpClient();
     this.connected = false;
     client.BeginConnect(adress, port, new AsyncCallback(OnConnect), null);
 }
Exemplo n.º 7
0
        /*
         * Metodo invocato dall'evento Click del pulsante
         * Conversione dei parametri e avvio del tentativo di connessione
         */
        private void ConnectionClick(object sender, RoutedEventArgs e)
        {
            string indirizzo = IPTextBox1.Text + "." + IPTextBox2.Text + "." + IPTextBox3.Text + "." + IPTextBox4.Text;

            if (indirizzo == "0.0.0.0")
            {
                MessageBox.Show("Impossibile connettersi all'host specificato", "Attenzione", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            Int32 porta;

            try {
                porta = Convert.ToInt32(PortTextBox.Text);
            }
            catch (FormatException) {
                porta = 2000;
            }
            catch (OverflowException) {
                porta = 2000;
            }

            // Verifica dell'esistenza di una tab connessa allo stesso indirizzo
            foreach (Window window in System.Windows.Application.Current.Windows)
            {
                if (window is MultiMainWindow)
                {
                    MultiMainWindow m = window as MultiMainWindow;
                    if (m.connessioni_attive.Contains(indirizzo))
                    {
                        MessageBox.Show("Connessione già effettuata verso " + indirizzo);
                        return;
                    }
                }
            }

            Console.WriteLine("Connessione verso: {0} - {1}", indirizzo, porta);

            try {
                client = new TcpClient();
                Client_info info = new Client_info();
                info.client    = client;
                info.indirizzo = indirizzo;
                // Richiesta di connessione asincrona per non bloccare l'interfaccia
                this.connectionResult = client.BeginConnect(indirizzo, porta, new AsyncCallback(requestConnection), info);
                // Disabilitazione dell'interfaccia per evitare più richieste contemporanee
                ConnectionButton.IsEnabled = false;
                IPTextBox1.IsEnabled       = IPTextBox2.IsEnabled = IPTextBox3.IsEnabled = IPTextBox4.IsEnabled = false;
                PortTextBox.IsEnabled      = false;
                this.Cursor = Cursors.AppStarting;
            }
            catch (SecurityException) {
                MessageBox.Show("Accesso negato: permessi non sufficienti", "Attenzione", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (ObjectDisposedException) {
                MessageBox.Show("Errore di connessione", "Attenzione", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (ArgumentOutOfRangeException) {
                MessageBox.Show("Numero di porta non valido, valori ammessi: 1-65536", "Attenzione", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (SocketException) {
                MessageBox.Show("Impossibile stabilire una connesione", "Attenzione", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Exemplo n.º 8
0
        /*Associata all'evento click del Bottone Connetti, tenta la connessione all'indirizzo IP specificato
         * -controlla che l'ip sia valido
         * -inserisce l'ip nel file di storia
         * -controlla se esiste già una connessione attiva a tale indirizzo
         * -si tenta la connessione con BeginConnect e si fa una chiamata asincrona a ConnectionRequest
         * che in caso di successo, crea una MainWindow oppure una nuova tab da aggiungere ad essa.
         */
        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            string input = txtAddress1.Text;

            if (!IsValidIP(input))
            {
                MessageBox.Show("Inserire un ip valido", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string address = input;

            //controlla se indirizzo IP esiste già nel file, e non lo scrivere nel caso
            FileInfo     fail   = new FileInfo("IPdatabase.txt");
            FileStream   s      = fail.Open(FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(s);
            string       line;
            bool         exists = false;

            while ((line = reader.ReadLine()) != null)
            {
                if (address == line)
                {
                    exists = true;
                }
            }
            s.Close();


            if (!exists)
            {
                FileInfo     f      = new FileInfo("IPdatabase.txt");
                StreamWriter writer = f.AppendText();
                writer.WriteLine(address); //scrivo nel file l'indirizzo
                IPaddresses.Add(address);  //scrivo nella lista l'indirizzo
                writer.Close();
            }



            if (address == "0.0.0.0")
            {
                MessageBox.Show("Impossibile connettersi all'host specificato", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            Int32 port;

            try
            {
                // Conversione del testo della porta in Int32 e gestione delle eventuali eccezioni
                port = Convert.ToInt32(txtPort.Text);
            }
            catch (FormatException)
            {
                port = 2000;
            }
            catch (OverflowException)
            {
                port = 2000;
            }

            // Verifica dell'eventuale esistenza di un tab connesso allo stesso indirizzo
            foreach (Window w in System.Windows.Application.Current.Windows)
            {
                if (w is MainWindow)
                {
                    MainWindow m = w as MainWindow;

                    if (m.ActiveConnectionsIPList.Contains(address))
                    {
                        MessageBox.Show("Il server del quale si è inserito l'indirizzo IP è già collegato ");
                        return;
                    }
                }
            }
            // Nel caso in cui l'indirizzo indicato non sia relativo ad alcun server già connesso, si procede normalmente
            Console.WriteLine("Connessione verso: {0} - {1}", address, port);

            try
            {
                client = new TcpClient();  //creo un oggetto TCPClient per poter usare i suoi metodi che mi permettono di creare
                                           //un socket verso il server.

                //l'oggetto properties permette al thread che gestisce il
                ClientProperties properties = new ClientProperties();
                properties.client  = client;
                properties.address = address; //address estratto dalla textbox

                // Invia una richiesta di connessione asincrona: il client non si blocca in attesa del risultato
                // La callback specificata come parametro viene lanciata quando l'operazione di connessione è completa

                this.connectionResult = client.BeginConnect(address, port, new AsyncCallback(ConnectionRequest), properties);

                // Disabilitazione dell'interfaccia per evitare richieste simultanee che non sono gestibili
                ConnectButton.IsEnabled  = false;
                txtAddress1.IsEnabled    = false;
                txtPort.IsEnabled        = false;
                IPaddressesBox.IsEnabled = false;
                this.Cursor = Cursors.AppStarting; // Cursore relativo ad un'app appena lanciata
            }
            catch (SecurityException)
            {
                MessageBox.Show("Accesso negato: non hai i permessi necessari", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (ObjectDisposedException)
            {
                MessageBox.Show("Errore di connessione", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Numero di porta non valido. I valori ammessi sono [1 - 65536]", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (SocketException)
            {
                MessageBox.Show("Connessione fallita", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Funzione invocata dall'evento di pressione del tasto Connetti.
        /// Cerca di instaurare una connessione con il server i cui parametri sono indicati nei campi della finestra.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Evento di pressione del tasto "Connetti" </param>
        private void C_ConnectButton(object sender, RoutedEventArgs e)
        {
            string address = txtAddress1.Text + "." + txtAddress2.Text + "." + txtAddress3.Text + "." + txtAddress4.Text;

            if (address == "0.0.0.0")
            {
                MessageBox.Show("Impossibile connettersi all'host specificato", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            Int32 port;

            try
            {
                // Conversione del testo della porta in Int32 e gestione delle eventuali eccezioni
                port = Convert.ToInt32(txtPort.Text);
            }
            catch (FormatException)
            {
                port = 2000;
            }
            catch (OverflowException)
            {
                port = 2000;
            }

            // Verifica dell'eventuale esistenza di un tab connesso allo stesso indirizzo
            foreach (Window w in System.Windows.Application.Current.Windows)
            {
                if (w is MainWindow)
                {
                    MainWindow m = w as MainWindow;

                    if (m.ActiveConnections.Contains(address))
                    {
                        MessageBox.Show("Il server del quale si è inserito l'indirizzo IP è già collegato ");
                        return;
                    }
                }
            }
            // Nel caso in cui l'indirizzo indicato non sia relativo ad alcun server già connesso, si procede normalmente
            Console.WriteLine("Connessione verso: {0} - {1}", address, port);

            try
            {
                client = new TcpClient();
                ClientProperties properties = new ClientProperties();
                properties.client  = client;
                properties.address = address;

                // Invia una richiesta di connessione asincrona: il client non si blocca in attesa del risultato
                // La callback specificata come parametro viene lanciata quando l'operazione di connessione è completa
                this.connectionResult = client.BeginConnect(address, port, new AsyncCallback(ConnectionRequest), properties);

                // Disabilitazione dell'interfaccia per evitare richieste simultanee che non sono gestibili
                ConnectButton.IsEnabled = false;
                txtAddress1.IsEnabled   = txtAddress2.IsEnabled = txtAddress3.IsEnabled = txtAddress4.IsEnabled = false;
                txtPort.IsEnabled       = false;
                this.Cursor             = Cursors.AppStarting; // Cursore relativo ad un'app appena lanciata
            }
            catch (SecurityException)
            {
                MessageBox.Show("Accesso negato: non hai i permessi necessari", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (ObjectDisposedException)
            {
                MessageBox.Show("Errore di connessione", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Numero di porta non valido. I valori ammessi sono [1 - 65536]", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (SocketException)
            {
                MessageBox.Show("Impossibile stabilire una connessione", "Attenzione!", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }