TCP Connection Server (127.0.0.1) Why are you locking in this line?

0

I'm trying to create a chat with client and server in C #, but I'm having trouble in this line:

client = servidor.AcceptTcpClient(); //Espera conexão

I'll post my code here to see if any of you can figure out what error it's making it hangs.

private void Servidor() {
    ip = textBox1.Text;
    servidor = new TcpListener(IPAddress.Parse(ip), port); //Cria endpoint com ip e porta
    servidor.Start();
    richTextBox1.Text = "[Servidor] Esperando conexão...";
    client = servidor.AcceptTcpClient(); //Espera conexão
    richTextBox1.Text += "\n[Servidor] Client conectado!";
    Recebendo();
}

void Button1Click(object sender, System.EventArgs e)
{
    Servidor();
}
private void Recebendo() {
    try {
        byte[] bytes = new byte[256]; //Buffer para a trânsferência de mensagens
        int count;
        while(true) {
            NetworkStream stream = client.GetStream(); //Pega stream do client
            while((count = stream.Read(bytes, 0, bytes.Length)) > 0) //recebe até‚ que não existam mais bytes para ler
            {
                mensagemEntrada = Encoding.ASCII.GetString(bytes, 0, count); //converte os bytes recebidos do buffer em uma string
                richTextBox1.Text += "\n[Client] " + mensagemEntrada;
            }
        }
    } catch(System.Exception ex) {
        MessageBox.Show(ex.ToString());
    }
    public void Desconectar() {
        client.Close(); //fecha conexão
        servidor.Stop(); // para de escutar conexões
        richTextBox1.Text += "Conexão encerrada!";
    }
    
asked by anonymous 17.09.2017 / 02:13

1 answer

1

There is nothing wrong. The client = servidor.AcceptTcpClient(); line locks until you receive a connection. See the example below:

Server

class Servidor {
    static void Main(string[] args) {
        string ip = "127.0.0.1";
        var porta = 13000;
        var servidor = new TcpListener(IPAddress.Parse(ip), porta);
        servidor.Start();

        Console.WriteLine("Aguardando conexão...");
        using (var cliente = servidor.AcceptTcpClient()) {
            var streamEntrada = cliente.GetStream();
            var buffer = new byte[cliente.ReceiveBufferSize];
            var bytesLidos = streamEntrada.Read(buffer, 0, cliente.ReceiveBufferSize);
            var dadosRecebidos = Encoding.ASCII.GetString(buffer, 0, bytesLidos);

            Console.WriteLine($"Mensagem recebida: {dadosRecebidos}");
        }
        servidor.Stop();
    }
}

Customer

class Cliente {
    static void Main(string[] args) {
        var ip = "127.0.0.1";
        var port = 13000;
        using (var cliente = new TcpClient()) {
            cliente.Connect(ip, port);
            if (cliente.Connected) {
                var streamSaida = cliente.GetStream();
                var bytesToSend = ASCIIEncoding.ASCII.GetBytes("Lorem ipsum dolor sit amet, consectetur adipiscing elit");
                streamSaida.Write(bytesToSend, 0, bytesToSend.Length);
                cliente.Close();
            }
        }
    }
}

Run the Server first and then the Client and you will see the message being sent from one to the other. Note that only after the Client connection is the var cliente = servidor.AcceptTcpClient() line unlocked.

For constant reception of data coming from the client, it is necessary to place the code that receives the connections in a while loop.

I took the liberty of changing some passages in the code.

Source:

  

link

    
19.09.2017 / 19:57