What if I want to send and receive a "package"?

Asked

Viewed 293 times

2

I put a mini server test online and everything worked out, the problem is that I want to send integers, booleans, strings, etc... So far I only know how to send string, how to take the first steps? For now I’m wearing this:

string dataFromServer = await serverReader.ReadLineAsync(); //Aguardando mensagens

I would like to send packets with an integer indicating its id so I know the structure and the rest undefined.

1 answer

2


Icarus,

To read data that are not strings you cannot use a Streamreader as in the example you put. It is possible to contain values also within the string, but this will depend on the implementation of an own protocol for such.

Currently it is possible to read any type of data through socket using the Socket class itself and the methods "Receive, Receivefrom, Receivemessagefrom" and its asynchronous variants.

These methods take as parameter an array of byte type and return an integer corresponding to the number of bytes received.

Using the function and storing the bytes you can use the conversion functions contained in the Bitconverter class to generate one of the primitive types implemented by . NET Framework.

Following example (educational purpose only, code not suitable for production environment):

var listener = new TcpListener(8080);
listener.Start();

while (true)
{
    const int buffer_length = 1024;
    byte[] dados = new byte[buffer_length];

    Socket cliente = listener.AcceptSocket();

    if (!cliente.Connected) continue;

    int recv_length = cliente.Receive(dados, buffer_length, SocketFlags.None);

    if(recv_length > 0)
    {
        try
        {
            Int32 dado_recebido = BitConverter.ToInt32(dados, 0);
            Console.WriteLine("Recebi um inteiro de 32 bits: " + dado_recebido.ToString());
        }
        catch(Exception ex)
        {
            Console.WriteLine("Não foi possível processar a mensagem recebida.");
            Console.WriteLine("Motivo: " + ex.Message);
        }

        cliente.Close();
    }
}

I hope I’ve been able to help you.

  • great! Very fucking, one of my questions was related to how I would convert bytes into other things :D

Browser other questions tagged

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