TCP Server Connection (127.0.0.1) Why are you crashing on this line?

Asked

Viewed 176 times

0

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

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

I’ll post my code here to see if any of you can figure out the mistake you’re 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!";
    }
  • If you don’t want it to lock, you’ll have to use a function async.

1 answer

1

There’s nothing wrong. The line client = servidor.AcceptTcpClient(); blocks until you receive some 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();
    }
}

Client

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’s connection is the line var cliente = servidor.AcceptTcpClient()is unlocked.

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

I took the liberty of altering some excerpts in the code.

Source:

https://msdn.microsoft.com/pt-br/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110). aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.