簡體   English   中英

如何從udp數據包解析具有相同結構的消息?

[英]How to parsing message with same struct from udp packet?

我的應用程序正在監聽udp端口,並且使用此結構接收到一些消息。 結構條目:

{
    long price;
    char type;
    char flag;
    int amount;
    long time;
}

我收到二進制消息,但是我怎么解析? 我知道不安全的方法,但是對我來說,這是不合適的。 我有這個功能:

[StructLayout(LayoutKind.Sequential, Pack = 1)]    
unsafe struct MyStruct
{
    public long price;
    public char type;
    public char flag;
    public int amount;
    public long time;

    public fixed byte OptionalBytes[50];
    public fixed int OptionalInts[10];

    public static MyStruct Deserialize(byte[] data)
    {
        fixed (byte* pData = &data[0])
        {
            return *(MyStruct*)pData;
        }
    }
}

您可以將UDP數據報的byte[]包裝在MemoryStream對象中,然后將其包裝在BinaryReader 這樣您就可以根據需要閱讀各個字段。 例如:

struct MyStruct
{
    public long price;
    public char type;
    public char flag;
    public int amount;
    public long time;

    public byte[] OptionalBytes; // 50 bytes
    public int[] OptionalInts;   // 10 ints (i.e. 40 bytes)

    public static MyStruct Deserialize(byte[] data)
    {
        MyStruct result = new MyStruct();

        using (MemoryStream inputStream = new MemoryStream(data))
        using (BinaryReader reader = new BinaryReader(inputStream))
        {
            result.price = reader.ReadInt64();
            result.type = reader.ReadChar();
            result.flag = reader.ReadChar();
            result.amount = reader.ReadInt32();
            result.time = reader.ReadInt64();

            OptionalBytes = reader.ReadBytes(50);

            if (OptionalBytes == 50)
            {
                try
                {
                    result.OptionalInts = Enumerable.Range(0, 10)
                        .Select(i => reader.ReadInt32()).ToArray();
                }
                catch (EndOfStreamException)
                {
                    // incomplete...ignore
                }
            }
            else
            {
                // incomplete...ignore
                result.OptionalBytes = null;
            }
        }

        return result;
    }
}

注意:我為“可選”字段做了一些准備; 您的問題沒有說明如何處理這些問題,因此我無法確切知道這些問題的正確解決方案。 我認為上面的示例為您提供了足夠的一般技術知識,您可以自己弄清楚如何處理這些字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM