通过 UDP 套接字发送 class,这是将我的数据转换为字节的正确方法吗?

Send a class through UDP socket, is this the right way to convert into bytes my data?

我如何将我的信息转换成字节:

public byte[] ToByte()
        {
            // FORMAT
            // |Command|Name|x|y|

            List<byte> result = new List<byte>();

            result.AddRange(BitConverter.GetBytes((int)command_));
            result.AddRange(Encoding.UTF8.GetBytes(nickname_));
            result.AddRange(BitConverter.GetBytes(x_));
            result.AddRange(BitConverter.GetBytes(y_));

            return result.ToArray();
        }

您可以使用 BinaryFormatter...

[Serializable]
public class MyClass
{
    public int MyProperty { get; set; }
}

// On the sending side...
var myClass = new MyClass { MyProperty = 1 };

byte[] bytes = null;
using (var ms = new MemoryStream())
{
    var bf = new BinaryFormatter();
    bf.Serialize(ms, myClass);
    bytes = ms.ToArray();
}

// On the receiving side...
MyClass other = null;
using (var ms = new MemoryStream(bytes))
{
    var bf = new BinaryFormatter();
    other = (MyClass)bf.Deserialize(ms);
}

因为字符串可以是任意长度,所以您需要发送名称的长度,或者向数据包中添加一些内容以检测字符串的结尾。前缀长度可能是最简单和最直接的。

更新的构造函数和 To-bytes 方法:

    // Constructor for received packet
    public GameDataPacket(byte[] data)
    {

        int packetOffset = 0;

        this.command_ = (MultiplayerService.Command)BitConverter.ToInt32(data, packetOffset);
        packetOffset += 4;

        // read the length (in bytes) of the nickname
        int nickDataLength = BitConverter.ToInt32(data, packetOffset);
        packetOffset += 4;

        // read the nick name
        this.nickname_ = Encoding.UTF8.GetString(data, packetOffset, nickDataLength);
        packetOffset += nickDataLength;
        this.x_ = BitConverter.ToSingle(data,  packetOffset);
        packetOffset += 4;
        this.y_ = BitConverter.ToSingle(data,  packetOffset);
    }

    public byte[] ToByte()
    {
        // FORMAT
        // |Command|NameDataLength|Name|x|y|

        List<byte> result = new List<byte>();

        result.AddRange(BitConverter.GetBytes((int)command_));
        byte[] nicknameBytes = Encoding.UTF8.GetBytes(nickname_);
        result.AddRange(BitConverter.GetBytes(nicknameBytes.Length));
        result.AddRange(nicknameBytes);
        result.AddRange(BitConverter.GetBytes(x_));
        result.AddRange(BitConverter.GetBytes(y_));

        return result.ToArray();
    }