Send multiple variables at once socket

0

Using the method Socket.Send would have some way to send a package with eg an integer and a string at a time?

I've seen one such Packet that apparently was all I needed because I can turn it into an array of bytes and then turn back into packet but I could not use the namespace Microsoft.SmartDevice.Connectivity , it's as if it did not exist in the vineyard version of .NET . But does anyone have a better solution than this?

    
asked by anonymous 30.08.2016 / 08:11

1 answer

1

Icarus, according to the answer given in this question here :

Yes, it is possible. Just let you know the size in bytes of your content. So imagine that you sent a 32-bit integer and a string containing 10 bytes, respectively through a socket.

Edited (Adding method for transforming objects into array of bytes):

If you send the content, you must generate the bytes to be sent in the following way (as an example):

Int32 codigo = 123;
String conteudo = "teste123";

const int buffer_length = 1024;
byte[] dados = new byte[buffer_length];

dados = BitConverter.GetBytes(codigo);
Buffer.BlockCopy(conteudo.ToCharArray(), 0, dados, dados.Length, conteudo.Length);

Whoever receives it should read as follows (considering no spaces or any other characters among the bytes sent):

//Declara-se o buffer de recebimento de dados
const int buffer_length = 1024;
byte[] dados = new byte[buffer_length];

//Recebe-se os dados da socket cliente
int recv_length = cliente.Receive(dados, buffer_length, SocketFlags.None);

//Contador para controle de "Em qual byte paramos a leitura?"
int byte_inicial = 0;

//Recebemos o inteiro através de um array de bytes e convertemos ele.
Int32 inteiro_recebido = BitConverter.ToInt32(dados, 0);
//Logo acrescemos o seu tamanho em bytes ao total de bytes lido
byte_inicial += sizeof(Int32);

//Declaramos um buffer isolado para a string que vem a seguir
byte[] bytes_str_recebida = new byte[buffer_length];
//E copiamos ela no array de bytes recém declarado passando os parâmetros que 
// indicam onde no array original a string está e qual seu tamanho
Buffer.BlockCopy(dados, byte_inicial, bytes_str_recebida, 0, dados.Length - byte_inicial);

//E finalmente convertemos os bytes correspondentes ao texto recebido para o tipo String.
string str_recebida = bytes_str_recebida.ToString();

I've commented on the code (complete in the linked question) to make it easier to understand.

To add other types to the content is the same schema, just know where the content is and what its size in bytes.

I hope I have been able to help.

    
30.08.2016 / 12:27