C#⽹络数据编码与解码(EncoderandDecoder)
例⼦为在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 = _EncodeStart.Text.ToCharArray();        //将字符串转换为⼀组char数组
decoder
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;
}          }      }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。