Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've done the server-client connection, but now my goal is to make the connection automatically ... Can someone give me tips on how to do it?

Initially I made the connection with buttons, to create the server and for the connection of the client to the server


What I have tried:

public Form1()
            {
                InitializeComponent();

                IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());      //Vai buscar o IP do computador

                foreach(IPAddress address in localIP)
                    {
                    if(address.AddressFamily == AddressFamily.InterNetwork) // se o Ip corresponder com o IPv4 vai aparecer na txtbox o ip da maquina
                    {
                        textBox3.Text = address.ToString();
                    }
                }
            }

            private void button2_Click(object sender, EventArgs e) //Criar o server
            {
                TcpListener Listener = new TcpListener(IPAddress.Any,int.Parse( textBox4.Text)); // permite que a pass seja uma qualquer em numeros apenas
                Listener.Start();   
                client = Listener.AcceptTcpClient();
                STR = new StreamReader(client.GetStream());
                STW = new StreamWriter(client.GetStream());
                STW.AutoFlush = true; //buffering ilimitados. 
                                      //Quando AutoFlush é definido como false, StreamWriter fará uma quantidade limitada de buffering

                backgroundWorker1.RunWorkerAsync(); // Começar a receber dados em segundo plano
                backgroundWorker1.WorkerSupportsCancellation = true; // Capacidade de cancelar o ligacao



            }

            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Receber dados
            {
                while(client.Connected) //enquanto o cliente tiver conectado vai ler o que servidor diz em chat 
                {
                    try
                    {
                        receive = STR.ReadLine();
                        this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText("server: " + receive + "\n"); }));
                        receive = "";
                     }
                    catch(Exception x)
                    {
                        MessageBox.Show(x.Message.ToString());
                    }
                }
            }

            private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) // enviar dados
            {
                if(client.Connected) //enquanto o cliente tiver conectado pode escrever para o servidor
                {
                    STW.WriteLine(text_to_send);
                    this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText("cliente: " + text_to_send + "\n"); }));
                }
                else
                {
                    MessageBox.Show("Envio Falhado!");
                }

            }

            private void button3_Click(object sender, EventArgs e) //conectar ao servidor
            {
                client = new TcpClient();
                IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text)); // sincronizacao do IP com a porta
                try
                {
                    client.Connect(IP_End);
                    if(client.Connected)
                    {
                        textBox2.AppendText("Conectado ao servidor" + "\n");
                        STW = new StreamWriter(client.GetStream());
                        STR = new StreamReader(client.GetStream());
                        STW.AutoFlush = true;

                        backgroundWorker1.RunWorkerAsync(); // Começar a receber dados em background
                        backgroundWorker1.WorkerSupportsCancellation = true; // possibilidade de cancelar o fio

                    }
                }catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());
                }
            }

            private void button1_Click(object sender, EventArgs e) // botao de envio
            {
                if(text_to_send != "")
                {
                    text_to_send = textBox1.Text;
                    backgroundWorker2.RunWorkerAsync();
                }
                textBox1.Text = "";
            }
Posted
Updated 22-Mar-17 5:35am
Comments
[no name] 22-Mar-17 11:27am    
Okay so use some other event instead of a button click.

1 solution

so what's the Problem? Your EventHandler is a normal method you can call (on initialization or whenever you want it to happen). Or you can call it by "clicking the button from Code" e.b. by button.PerformClick()...
But I think your real Problem is, that your code has no separation of concerns at all....
I'd create a separate class to handle the Connection. Then let you Form use it. Maybe you will come up with a "Connect" and a "Disconnect" function.
If you would have structured your code a little, you wouldn't ask (yourself and us) such a question.
It's no offense, but from your question I'd say you should work more on your basic programming skills than on the problem at hand...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900