1

I am using visual studio 2019 and trying to send a structure through UDP in C# UI. However, I have not figured out yet how to convert structure with inner structures, arrays and enums to byte array to send it through UDP. Here is my Code;

namespace Sender
{
    public struct FMS
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public arc[] arcs;
        public UInt32 type;
        
    }
    public struct arc
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public location[] locs;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
        public sbyte[] length;
        public UInt32 fuel;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
        public char[] ids;
        public distance dist;
    }
    public struct location
    {
        public float x_axis;
        public float y_axis;
    }
    public enum distance
    {
        PEAK = 0,
        STEP
    }


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Send_Button_Click(object sender, EventArgs e)
        {
            Socket clientSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            IPAddress clientIpAddress = IPAddress.Parse("127.0.0.1");
            int clientPortNum = 60000;
            IPEndPoint clientEndPoint = new IPEndPoint(clientIpAddress, clientPortNum);
            clientSocket.Bind(clientEndPoint);

            IPAddress serverIpAddress = IPAddress.Parse("127.0.0.1");
            int serverPortNum = 50000;
            IPEndPoint serverEndPoint = new IPEndPoint(serverIpAddress, serverPortNum);

            // initialize the structures
            location loc1 = new location();
            loc1.x_axis = 1.0F;
            loc1.y_axis = 2.0F;

            location loc2 = new location();
            loc1.x_axis = 3.0F;
            loc1.y_axis = 4.0F;

            arc arc1 = new arc();
            arc1.locs = new location[] { loc1, loc2 };
            arc1.length = new sbyte[] { 1, 2, 3, 4 };
            arc1.fuel = 3500;
            arc1.ids = new char[] { 'a', 'b', 'c', 'd', 'e' };
            arc1.dist = distance.PEAK;


            location loc3 = new location();
            loc3.x_axis = 5.0F;
            loc3.y_axis = 6.0F;

            location loc4 = new location();
            loc4.x_axis = 7.0F;
            loc4.y_axis = 8.0F;

            arc arc2 = new arc();
            arc2.locs = new location[] { loc3, loc4 };
            arc2.length = new sbyte[] { 5, 6, 7, 8 };
            arc2.fuel = 7000;
            arc2.ids = new char[] { 'x', 'c', 'g', 'f', 'a' };
            arc2.dist = distance.STEP;

            FMS fmsObj = new FMS();
            fmsObj.arcs = new arc[] { arc1, arc2 };
            fmsObj.type = 1;

            //End of initialization of structures

            byte[] bytesToSend = // ???????
            clientSocket.SendTo(bytesToSend, serverEndPoint);
            clientSocket.Close();
        }
    }
}

And also, after I convert the structure to byte array how could I convert byte array back to structure?

I have finally managed to convert it to byte array with the code below

//send the structure in the byte array
BinaryFormatter formatter = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream()
{
   formatter.Serialize(stream,fmsObj);
   byte[] bytesToSend = stream.ToArray();
   clientSocket.SendTo(bytesToSend,serverEndPoint);
   clientSocket.Close();
}

If I do this, I face assembly issue when I try to receive the structure with the code below I have to add the assembly of the sender code to make the receiver code work.

//receive the structure in byte array
StructSender.Form1.FMS fmsObj = new StructSender.Form1.FMS();
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream(receivedBytes))
{
   fmsObj = (StructSender.Form1.FMS)formatter.Deserialize(stream);
}

I need to find a way that allows me to convert the structure I mentioned above to byte array, send it to the specific port then receive that byte array from that port and convert it back to the structure.

6
  • 1
    Do not use BinaryFormatter. Commented Mar 18, 2023 at 19:56
  • Also mind that UDP does not handle things like order of packets or missing packets. So even if you have a decent protocol, you need to implement those or switch to tcp. Commented Mar 18, 2023 at 20:08
  • Read something more about serialization and deserialization. Sending raw bytes from memory (or using binaryformatter) is very bad idea, avoid it. Take a look at fast and reliable formatters: protobuf, message pack or even system.text.json Commented Mar 18, 2023 at 20:52
  • "Visual Studio 2019" is the version of the IDE, not the language version of C# or framework you are using. Commented Mar 18, 2023 at 22:54
  • If you want to convert character array to struct, you can refer to this <stackoverflow.com/questions/30817645/byte-array-to-struct>. But if you want more help, you should tell us exactly what error your code reported when accepting struct? Commented Mar 21, 2023 at 6:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.