winform网络传输时候封包与解包心得

我这个不是一个很好的传输格式,希望可以得到各位的指点。

第一个字节代表:类型

第二个字节开始20字节代表:用户名

第21个字节开始20字节代表:密码

view source print ?
private void button1_Click(object sender, EventArgs e)
       {
           byte[] package = Pack();
           Unpack(package);
       }
        
       static int userlength = 20;
       static int passlength = 20;
       //打包
       private byte[] Pack()
       {
           byte[] buffer = new byte[1024];
           buffer[0] = 1;//类型
           byte[] username = Encoding.UTF8.GetBytes("Sam");//有长度限制
           byte[] userpass = Encoding.UTF8.GetBytes("Password");//有长度限制
 
           Array.Copy(username, 0, buffer, 1, username.Length);
           Array.Copy(userpass, 0, buffer, 1 + userlength, userpass.Length);
           return buffer;
       }
       //解包
       private void Unpack(byte[] buffer)
       {
           int type = buffer[0];
           byte[] username = new byte[userlength];
           byte[] userpass = new byte[passlength];
 
           Array.Copy(buffer, 1, username, 0, userlength);
           Array.Copy(buffer, 1 + userlength, userpass, 0, passlength);
           string strName = Encoding.UTF8.GetString(username).TrimEnd('\0');
           string strPass = Encoding.UTF8.GetString(userpass).TrimEnd('\0');
           Console.WriteLine("类型:" + type.ToString());
           Console.WriteLine("用户名:"+strName);
           Console.WriteLine("密码:" + strPass);
           Console.WriteLine("解包完成");
       }

最后效果:

你可能感兴趣的:(职场,休闲,java05086)