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

2

I ran a mini server test online and everything worked fine, 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 using this:

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

I would like to send packages with an integer indicating the id of it so I know the structuring and the rest undefined.

    
asked by anonymous 28.08.2016 / 18:01

1 answer

2

Icarus,

To read data other than strings you can not use a StreamReader as in the example that you put. It is possible to contain values also inside the string, but this will depend on the implementation of a protocol for that.

Currently it is possible to read any data type through socket using the Socket class itself and the "Receive, ReceiveFrom, ReceiveMessageFrom" methods and their asynchronous variants.

These methods are parameterized by 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 the .NET Framework.

Here's an 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 have been able to help you.

    
29.08.2016 / 12:36