Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

How to create a packet in C#

I always wondered how could a game generate a packet like this:

22 00 11 00 6D 79 75 73 65 72 6E 61 6D 65 00 00 00 00 00 00 6D 79 70 61 73 73 77 6F 72 64 00 00 00 00 00 00

LENGTH-HEADER-USERNAME-PASSWORD

In the game code what should be their function or how do they write something like that? Is it simply Encoding.ASCII.GetBytes("Some String Values")? Although I doubt it is written that way.

Every time I try to ask someone that, he thinks that I want to analyze packet. I don't - I want to know what I need to do in order to create a packet like the one above, in C#.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The sample code you've put should convert the string to a byte array. Depending which encoding you use (e.g. ASCII, Unicode, etc) you may get a different byte array from the same string.

The term packet is generally used when you're sending data through a network; but the packet itself is just the byte array.

The info you've got reads myUsername, myPassword. The below C# code will translate for you.

        byte[] packet = new byte[] { 0x22, 0x00, 0x11, 0x00, 0x6D, 0x79, 0x75, 0x73, 0x65, 0x72, 0x6E, 0x61, 0x6D, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x79, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        string test = Encoding.ASCII.GetString(packet);
        Console.WriteLine(test);
        Console.ReadKey();

So to create something similar I'd try:

    const int HeaderLength = 2;
    const int UsernameMaxLength = 16;
    const int PasswordMaxLength = 16;
    public static byte[] CreatePacket(int header, string username, string password)//I assume the header's some kind of record ID?
    {
        int messageLength = UsernameMaxLength + PasswordMaxLength + HeaderLength;
        StringBuilder sb = new StringBuilder(messageLength+ 2);
        sb.Append((char)messageLength);
        sb.Append(char.MinValue);
        sb.Append((char)header);
        sb.Append(char.MinValue);
        sb.Append(username.PadRight(UsernameMaxLength, char.MinValue));
        sb.Append(password.PadRight(PasswordMaxLength, char.MinValue));
        return Encoding.ASCII.GetBytes(sb.ToString()); 
    }

Then call this code with:

byte[] myTest = CreatePacket(17, "myusername", "mypassword");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...