How do I know if the customer sent me something?

2

I made this code here following some tutorials on the internet.

buttonAbrirConexão.Enabled = false;
TcpListener servidor = new TcpListener(6554);
servidor.Start();
while(true)
{
    Thread.Sleep(2500);
    if(servidor.Pending())
    {
    MessageBox.Show("Cliente conectado");
    Socket conexão = servidor.AcceptSocket();
    socketStream = new NetworkStream(conexão);
    escrever = new BinaryWriter(socketStream);
    ler = new BinaryReader(socketStream);
    escrever.Write("Alguma coisa");
    break;
    }
}

Before using ler.Read(), how will I know if the customer sent me something before? How do you know what he told you to do? String ? int ?

Is there a way to fire an asynchronous event every time a client tries to connect?

    
asked by anonymous 28.08.2016 / 02:39

1 answer

2

Without going into the merit of this code is adequate, even because I imagine it is just an initial attempt, the problem is to use Pending() . If you remove it the "server" will be waiting to receive something.

Now if you want to do asynchronous, the main change would be to take the asynchronous method AcceptSocketAsync() ", something like this:

buttonAbrirConexão.Enabled = false;
TcpListener servidor = new TcpListener(6554);
servidor.Start();
while(true) {
    MessageBox.Show("Cliente conectado");
    Socket conexão = await servidor.AcceptSocketAsync();
    socketStream = new NetworkStream(conexão);
    escrever = new BinaryWriter(socketStream);
    ler = new BinaryReader(socketStream);
    escrever.Write("Alguma coisa");
}

See an example .

There is no way to know what code is coming. This mechanism transmits bytes , not specific data. Only a previously agreed protocol can determine what the data is. The type of the fixed, can depend on position, can even have metadata informing what are the data types.

    
28.08.2016 / 04:29