C#网络编码

在网络通信中,很多情况下通信双方传达的都是字符信息。但是,字符信息并不能直接从网络的一端传递到另一端,这些字符信息首先需要被转换成一个字节序列后才能在网络中传输。将字符序列转换为字节序列的过程称为编码。当这些字节传送到网络的接收方时,接收方需要反过来将字节序列再转换为字符序列,这种过程称为解码。

下面是编码与解码的例子:

截图:

完整代码:

  1. namespace EncoderDecoderExample  
  2. {  
  3.     public partial class Form1 : Form  
  4.     {  
  5.         public Form1()  
  6.         {  
  7.             InitializeComponent();  
  8.             txt_EncodeStart.Text = "这是一条测试数据:abc,123ABC..。。\n test string";  
  9.         }  
  10.   
  11.         private void Form1_Load(object sender, EventArgs e)  
  12.         {  
  13.             //显示现有的编码类型   
  14.             foreach (EncodingInfo ei in Encoding.GetEncodings())  
  15.             {  
  16.                 Encoding en = ei.GetEncoding();  
  17.                 cbo_EncodeType.Items.Add(string.Format("{0}[{1}]", en.HeaderName, en.EncodingName));  
  18.             }  
  19.             cbo_EncodeType.SelectedIndex = cbo_EncodeType.FindString("gb2312");  
  20.         }  
  21.   
  22.         private void btn_EncodeAndDecode_Click(object sender, EventArgs e)  
  23.         {  
  24.             //编码   
  25.             string codeType = this.cbo_EncodeType.SelectedItem.ToString();  
  26.             codeType = codeType.Substring(0, codeType.IndexOf('['));        //获得编码类型 默认选择(gb2312)   
  27.             Encoder encoder = Encoding.GetEncoding(codeType).GetEncoder();  //获得一个 gb2312 编码类型的编码器   
  28.             char[] chars = this.txt_EncodeStart.Text.ToCharArray();         //将字符串转换为一组char数组   
  29.             byte[] bytes = new byte[encoder.GetByteCount(chars, 0, chars.Length, true)];    //声明一个长度为‘编码为byte后产生的字节数’   
  30.             encoder.GetBytes(chars, 0, chars.Length, bytes, 0, true);       //进行编码,将chars数组中的字符编码到byte数组中   
  31.             txt_EncodeOver.Text = Convert.ToBase64String(bytes);            //将 8 位无符号整数数组的值转换为其用 Base64 数字编码的等效字符串 显示到控件中。   
  32.   
  33.             //解码   
  34.             Decoder decoder = Encoding.GetEncoding(codeType).GetDecoder();      //获得编码类型为 gb2312 的解码器   
  35.             int charLen = decoder.GetChars(bytes, 0, bytes.Length, chars, 0);   //进行解码,将byte数组中的8位无符号整数转换为 char字符   
  36.             String strResult = "";  
  37.             foreach (char c in chars)  
  38.                 strResult += c.ToString();    
  39.             txt_DecodeOver.Text = strResult;  
  40.   
  41.         }  
  42.   
  43.   
  44.     }  
  45. }  

posted on   荣锋亮  阅读(155)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示