How do I know the client sent me something?

Asked

Viewed 115 times

3

I made this code here following some tutorials over 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 the ler.Read(), how do I know if the customer sent me something before? How to know also what he sent? String? int?

Is there a way to trigger an asynchronous event whenever a client tries to connect?

  • You need to read this: http://answall.com/q/101691/101

1 answer

3


Without getting into the merit of this code being adequate, because I imagine it’s just an initial attempt the problem is to use the 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 that:

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");
}

I put in the Github for future reference.

Take an example.

There is no way to know what code is coming. This mechanism transmits bytes, no specific data. Only a pre-combined protocol can determine what the data is. The type of the fixed being, may depend on position, may even have metadata stating what the data types are.

  • I did not understand this loop without checks that you put there, following this it will be only putting the message "Client connected" all the time, no?

  • The example is really spectacular, I did not know of that await instruction

  • It goes every time you have a connection, before what it did is take a data and shut down the server, it’s usually not what you want. Of course you have to have a way out, so I said that this code is bad and I indicated a better example.

  • I managed to make the server run between two computers, thanks!!! Now I have another question and I’ll take in the forum

Browser other questions tagged

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