Best Practice: generating and parsing network packets for a known protocol in C#?

左心房为你撑大大i 提交于 2019-12-23 03:55:24

问题


I tried asking a similar question recently however after several answers I realized it wasn't the correct thing to ask.

Is there a guide or a generally accepted practice for generating and parsing network packets based on an existing protocol like SMPP (Short Message Peer-to-Peer Protocol [Used for SMS Messages]) or various chat protocols like HOTLINE or IRC with C#.

One of the answers mentioned Google Protocol Buffers and a .NET version. After looking at that I realized that serialization is extremely useful if you have control over both ends (client and server). Where I would be following the protocol spec.

Generating In the past I have made a class or structure with properties that are part of the network packet / protocol:

// PSEUDO CODE
class NetworkObject 
{
    private int length;
    private string data;

    // ...

    public byte[] GetBytes() 
    {
        // Convert string and int to byte array
        return byte array;
    }
}

The class has a byte[] GetBytes() method which I call once I've set the appropriate properties. I take that byte array and send it over the network. In my previous question one of the answers suggested storing the data in a memory stream or bytestream which seems like a better idea.

It seems like my byte array method is probably slower than passing a network stream to a method that writes the packet data according to class properties directly to the stream. Which is what I will probably do unless I'm missing something really big here.

Parsing When parsing I use various case statements to step through the various PDUs and generate a NetworkObject with the appropriate properties populated and do with it as I see fit.


回答1:


Why don't you try Serialization of objects?



来源:https://stackoverflow.com/questions/1329855/best-practice-generating-and-parsing-network-packets-for-a-known-protocol-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!