I write the number to the byte array and then send the array to the socket to the client.

uint a = 1; byte[] b = BitConverter.GetBytes(a); handler.Send(b); 

But how to write several variables to an array of bytes, such as a string, uint, int, and others?

    2 answers 2

    I will offer another way:

     uint a = 1; int b = 2; using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { writer.Write(a); writer.Write(b); var bytes = stream.ToArray(); handler.Send(bytes); } 

    BinaryWriter Write method has many overloads.

    PS: You can read from a byte array by analogy using BinaryReader .

    • Thank you, more convenient way) And you could give an example of reading, I do not understand a bit. - Alexander
    • Here is getting bytes = new byte[1024]; bytesRec = handler.Receive(bytes); bytes = new byte[1024]; bytesRec = handler.Receive(bytes); how to get uint from stream? - Alexander
    • @ Alexander - how did you receive it before? And in general, do not ask in the comments, ask a new question (create a new topic). - Alexander Petrov
     uint a = 1; byte[] a1 = BitConverter.GetBytes(a); double b = 1.234; byte[] a2 = BitConverter.GetBytes(b); byte[] arr = new byte[a1.Length + a2.Length]; Array.Copy(a1, 0, arr, 0, a1.Length); Array.Copy(a2, 0, arr, a1.Length, a2.Length); handler.Send(arr); 
    • Thanks, and maybe there is a shorter way? I just need to add a large number of values ​​to the array, and if you use this method, the code will be too large - Alexander
    • @ Alexander Have an array of values ​​and process them in a loop. - Igor