博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#串口通信—传输文件测试
阅读量:6069 次
发布时间:2019-06-20

本文共 6715 字,大约阅读时间需要 22 分钟。

说明:该程序可能不具备实用性,仅测试用。

一、使用虚拟串口工具VSPD虚拟两个串口COM1和COM2

二、约定

占一个字节,代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace COMClient{    ///     /// 约定    ///     public enum Protocol    {        Client端发送文件名 = 0,        Client端发送数据块 = 1,        Client端发送最后一个数据块 = 2,        Server端本次接收完毕 = 3,        Server端结束 = 4    }}
View Code

三、功能说明:

 COMClient程序监听COM1串口,COMServer程序监听COM2串口。COMClient先择文件,发送,COMServer接收文件。数据分多次发送,每次发送的数据,通过第一个字节判断发送的这段数据是干啥的,后面的字节是数据本身。

四、COMClient端发送文件

代码:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO.Ports;using System.IO;using System.Threading;namespace COMClient{    public partial class Form1 : Form    {        #region 变量        ///         /// 串口资源        ///         private static SerialPort serialPort = null;        ///         /// 文件        ///         private static FileStream fs = null;        private static long index = 0;        private static long blockCount;        private static int size = 4095;        private static DateTime dt;        #endregion        #region Form1        public Form1()        {            InitializeComponent();        }        #endregion        #region Form1_Load        private void Form1_Load(object sender, EventArgs e)        {            serialPort = new SerialPort("COM1");            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);            serialPort.Open();        }        #endregion        #region btnConn_Click        private void btnConn_Click(object sender, EventArgs e)        {            if (openFileDialog1.ShowDialog() == DialogResult.OK)            {                dt = DateTime.Now;                fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);                blockCount = (fs.Length - 1) / size + 1;                List
bList = new List
(); bList.Add((int)Protocol.Client端发送文件名); bList.AddRange(ASCIIEncoding.UTF8.GetBytes(openFileDialog1.FileName)); byte[] bArr = bList.ToArray(); serialPort.Write(bArr, 0, bArr.Length); } } #endregion ///
/// 接收串口数据事件 /// public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (serialPort.BytesToRead == 0) return; int bt = serialPort.ReadByte(); switch (bt) { case (int)Protocol.Server端本次接收完毕: if (index != blockCount - 1) { byte[] bArr = new byte[size + 1]; bArr[0] = (int)Protocol.Client端发送数据块; fs.Read(bArr, 1, size); index++; Thread.Sleep(1); serialPort.Write(bArr, 0, bArr.Length); } else { byte[] bArr = new byte[fs.Length - (size * index) + 1]; bArr[0] = (int)Protocol.Client端发送最后一个数据块; fs.Read(bArr, 1, bArr.Length - 1); index++; serialPort.Write(bArr, 0, bArr.Length); } break; case (int)Protocol.Server端结束: index = 0; double totalSeconds = DateTime.Now.Subtract(dt).TotalSeconds; MessageBox.Show("完成,耗时" + totalSeconds + "秒,速度" + (fs.Length / 1024.0 / totalSeconds).ToString("#.0") + "KB/S"); fs.Close(); fs.Dispose(); break; } } }}
View Code

五、COMServer端接收文件

代码:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO.Ports;using System.IO;namespace COMServer{    public partial class Form1 : Form    {        #region 变量        ///         /// 串口资源        ///         private static SerialPort serialPort = null;        ///         /// 文件        ///         private static FileStream fs = null;        #endregion        #region Form1        public Form1()        {            InitializeComponent();        }        #endregion        #region Form1_Load        private void Form1_Load(object sender, EventArgs e)        {            serialPort = new SerialPort("COM2");            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);            serialPort.Open();        }        #endregion        ///         /// 接收串口数据事件        ///         public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)        {            if (serialPort.BytesToRead == 0) return;            #region 接收数据            int bt = serialPort.ReadByte();            List
bList = new List
(); while (serialPort.BytesToRead > 0) { byte[] bArr = new byte[serialPort.BytesToRead]; serialPort.Read(bArr, 0, bArr.Length); bList.AddRange(bArr); } byte[] receiveData = bList.ToArray(); #endregion switch (bt) { case (int)Protocol.Client端发送文件名: string path = ASCIIEncoding.UTF8.GetString(receiveData); string fileName = Path.GetFileName(path); fs = new FileStream(@"d:\_临时文件\COM测试" + fileName, FileMode.Create, FileAccess.Write); byte[] bArr = new byte[1]; bArr[0] = (int)Protocol.Server端本次接收完毕; serialPort.Write(bArr, 0, bArr.Length); break; case (int)Protocol.Client端发送数据块: fs.Write(receiveData, 0, receiveData.Length); fs.Flush(); bArr = new byte[1]; bArr[0] = (int)Protocol.Server端本次接收完毕; serialPort.Write(bArr, 0, bArr.Length); break; case (int)Protocol.Client端发送最后一个数据块: fs.Write(receiveData, 0, receiveData.Length); fs.Flush(); bArr = new byte[1]; bArr[0] = (int)Protocol.Server端结束; serialPort.Write(bArr, 0, bArr.Length); fs.Close(); fs.Dispose(); break; } } }}
View Code

 

转载于:https://www.cnblogs.com/s0611163/p/4137943.html

你可能感兴趣的文章
LINUX内核调试过程
查看>>
【HDOJ】3553 Just a String
查看>>
Java 集合深入理解(7):ArrayList
查看>>
2019年春季学期第四周作业
查看>>
paip.提升性能---并行多核编程哈的数据结构list,set,map
查看>>
[转]mongodb与mysql相比的优缺点
查看>>
未在本地计算机上注册“Microsoft.Ace.OleDb.12.0”提供程序解决办法
查看>>
PHP and java
查看>>
sharepoint 2010 自定义页面布局
查看>>
〖Linux〗Android NDK调用已编译好的C/C++动态连接库(so文件)
查看>>
MD5编码工具类 MD5Code.java
查看>>
VB.NET TextBox 只允许输入1-100之间的整数 简洁篇
查看>>
UNIX网络编程读书笔记:端口号、套接口对和套接口
查看>>
数值积分初步
查看>>
ADS错误the session file 'C:\user\username\default-1-2-0-0.ses' could not be loaded解决办法
查看>>
在MVC应用程序中,怎样删除上传的文件
查看>>
asp.net报错“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”的解决办法...
查看>>
localForage——轻松实现 Web 离线存储
查看>>
SharePoint 中用户控件的开发及应用
查看>>
10分钟学会搭建Android开发环境 Eclipse: The import android.support cannot be resolved
查看>>