日期:2014-05-18 浏览次数:21222 次
comport.ReadTimeout = 30; comport.ReceivedBytesThreshold = 5; comport.DataReceived += new SerialDataReceivedEventHandler(comport_DataReceived);
private void send_Click(object sender, EventArgs e) { byte[] data = ASCIIEncoding.GetEncoding("gb2312").GetBytes(sdtext.Text.ToString()); if (mycomm.IsOpen) { mycomm.Write(data,0,data.Length); mycomm.WriteLine("\r"); } } //接收 private void mycomm_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int DataLength = mycomm.BytesToRead;//获取接受缓冲区中数据的字节数 int i = 0; StringBuilder strb = new StringBuilder(); while (i < DataLength) { byte[] dbs = new byte[2048]; int len = mycomm.Read(dbs,0,2048);//从输入缓冲区中读取2048个字节,并将这些字节写入到dbs[]数组中 strb.Append(ASCIIEncoding.GetEncoding("gb2312").GetString(dbs, 0, len)); i += len; } revtext.Text += strb; }
------解决方案--------------------
我用的是 事件驱动模式,发送事件,把sdtext.Text的文本用gb2312的编码方式转换成字节码;
接受方,用while处理,把字节码用gb2312的编码方式解码成String字符串,再把字符串显示到revtext.Text 里!
------解决方案--------------------
传送门