C# 网络数据编码与解码(Encoder and Decoder)

该例子为在C#中对网络数据编码与解码。


引用《网络应用编程(第二版)》49页的前面的话如下:

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


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


截图:


完整代码:

namespace EncoderDecoderExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            txt_EncodeStart.Text = "这是一条测试数据:abc,123ABC..。。\n test string";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //显示现有的编码类型
            foreach (EncodingInfo ei in Encoding.GetEncodings())
            {
                Encoding en = ei.GetEncoding();
                cbo_EncodeType.Items.Add(string.Format("{0}[{1}]", en.HeaderName, en.EncodingName));
            }
            cbo_EncodeType.SelectedIndex = cbo_EncodeType.FindString("gb2312");
        }

        private void btn_EncodeAndDecode_Click(object sender, EventArgs e)
        {
            //编码
            string codeType = this.cbo_EncodeType.SelectedItem.ToString();
            codeType = codeType.Substring(0, codeType.IndexOf('['));        //获得编码类型 默认选择(gb2312)
            Encoder encoder = Encoding.GetEncoding(codeType).GetEncoder();  //获得一个 gb2312 编码类型的编码器
            char[] chars = this.txt_EncodeStart.Text.ToCharArray();         //将字符串转换为一组char数组
            byte[] bytes = new byte[encoder.GetByteCount(chars, 0, chars.Length, true)];    //声明一个长度为‘编码为byte后产生的字节数’
            encoder.GetBytes(chars, 0, chars.Length, bytes, 0, true);       //进行编码,将chars数组中的字符编码到byte数组中
            txt_EncodeOver.Text = Convert.ToBase64String(bytes);            //将 8 位无符号整数数组的值转换为其用 Base64 数字编码的等效字符串 显示到控件中。

            //解码
            Decoder decoder = Encoding.GetEncoding(codeType).GetDecoder();      //获得编码类型为 gb2312 的解码器
            int charLen = decoder.GetChars(bytes, 0, bytes.Length, chars, 0);   //进行解码,将byte数组中的8位无符号整数转换为 char字符
            String strResult = "";
            foreach (char c in chars)
                strResult += c.ToString();  
            txt_DecodeOver.Text = strResult;

        }


    }
}

以上为完整代码,若不能正确编译,可直接下载打包文件进行编译:http://download.csdn.net/source/3464726

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Andrew_wx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值