最近闲来无事写了一个串口转网口的模拟机程序:
实现原理创建tcpserver监听端,接收客户端发送过来的信息,在通过com口转发出去。同样收到串口数据在通过服务端转发给客户端 如图

串口发送端代码:

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.Threading;namespace SerailPortReciv
{public partial class Form1 : Form{#region Varprivate SerialPort EntitySerial = null;private Thread ThreadRecive = null;private Queue<ReciveInfo> ReciveQueue = new Queue<ReciveInfo>();private byte[] ReciveBuffer = new byte[1024 * 2];private bool IsLoopBool = false;private int RecivePacketNU = 0;private double ReciveBytesNU = 0;private SynchronizationContext Context;private int SendPacketNu = 0;private Double SendBytesNu = 0;private byte[] SendDataBytsBuffer = null;private int SleepTiming = 0;private Thread ThreadSendData = null;private bool IsLoopSendData = false;private bool IsRealShowRecInfo = false;#endregionpublic Form1(){InitializeComponent();Context = SynchronizationContext.Current;}private void Form1_Load(object sender, EventArgs e){comboBoxOddEvent.SelectedIndex = 1;}private void btnOpenSerail_Click(object sender, EventArgs e){if (btnOpenSerail.Text == "开启串口"){if (!InitSerialPort()){MessageBox.Show("端口打开失败!" + txtCOM.Text);return;}IsRealShowRecInfo = checkBoxRealShowInfo.Checked;btnOpenSerail.Text = "关闭串口";}else{CloseCom();btnOpenSerail.Text = "开启串口";}}private bool InitSerialPort(){Parity par = Parity.None;if (comboBoxOddEvent.SelectedItem != null){switch (comboBoxOddEvent.SelectedItem.ToString().ToLower()){case "even":par = Parity.Even;break;case "none":par = Parity.None;break;case "odd":par = Parity.Odd;break;default:par = Parity.None;break;}}StopBits stopBit = StopBits.None;switch (txtStopBit.Text){case "1":stopBit = StopBits.One;break;case "1.5":stopBit = StopBits.OnePointFive;break;case "2":stopBit = StopBits.Two;break;default:stopBit = StopBits.None;break;}try{EntitySerial = new SerialPort(txtCOM.Text.ToUpper(), int.Parse(txtBaudRate.Text), par, int.Parse(txtDataBit.Text), stopBit);EntitySerial.Open();}catch (Exception){return false;}IsLoopBool = true;ThreadRecive = new Thread(ReciveMethod);ThreadRecive.IsBackground = true;ThreadRecive.Start();return true;}/// <summary>/// 接收数据线程/// </summary>void ReciveMethod(){while (IsLoopBool){int recNU = EntitySerial.BytesToRead;if (recNU > 0){int reciveNu = EntitySerial.Read(ReciveBuffer, 0, recNU);ReciveInfo entity = new ReciveInfo();entity.Buffer = new byte[reciveNu];entity.TimerString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");Array.Copy(ReciveBuffer, entity.Buffer, reciveNu);if (IsRealShowRecInfo){ShowEntityInfo(entity);}else{ReciveQueue.Enqueue(entity);}RecivePacketNU++;ReciveBytesNU += reciveNu;Context.Post(ret => { labReciveInfo.Text = string.Format("{0}/{1}", RecivePacketNU, ReciveBytesNU); }, null);}}}/// <summary>/// 关闭串口/// </summary>void CloseCom(){RecivePacketNU = 0;ReciveBytesNU = 0;Context.Post(ret => { labReciveInfo.Text = "总包数/总字节数"; }, null);IsLoopBool = false;if (EntitySerial != null){EntitySerial.Close();}EntitySerial = null;if (ThreadRecive != null && ThreadRecive.IsAlive){ThreadRecive.Abort();}}private void Form1_FormClosing(object sender, FormClosingEventArgs e){CloseCom();CloseSendData();}/// <summary>/// 显示接收到的数据/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btnShowRecive_Click(object sender, EventArgs e){lock (ReciveQueue){while (ReciveQueue.Count > 0){ShowEntityInfo(ReciveQueue.Dequeue());Thread.Sleep(10);}}}private void ShowEntityInfo(ReciveInfo recv){Context.Post(ret =>{txtShowRecive.AppendText(string.Format("[{0}] # Recive \r\n", recv.TimerString));txtShowRecive.AppendText(GetBufferFormatHex(recv.Buffer) + "\r\n");txtShowRecive.AppendText("\r\n");}, null);}private string GetBufferFormatHex(byte[] bts){StringBuilder sb = new StringBuilder();foreach (byte itemBt in bts){sb.Append(itemBt.ToString("X2") + " ");}return sb.ToString();}#region  定时发送数据private void btnSendData_Click(object sender, EventArgs e){if (btnSendData.Text == "发送数据"){bool retBool = int.TryParse(txtSendTiming.Text, out  this.SleepTiming);if (!retBool){MessageBox.Show("定时发送时间不合法!");return;}try{SendDataBytsBuffer = GetByteByHexString(txtSendData.Text);}catch{MessageBox.Show("待发送数据有误!");return;}if (checkBoxTimnigSend.Checked){IsLoopSendData = true;ThreadSendData = new Thread(ProcSendData);ThreadSendData.IsBackground = true;ThreadSendData.Start();btnSendData.Text = "停止";}else{try{txtShowRecive.AppendText(string.Format("[{0}] # Send \r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));EntitySerial.Write(SendDataBytsBuffer, 0, SendDataBytsBuffer.Length);txtShowRecive.AppendText(GetBufferFormatHex(SendDataBytsBuffer) + "[OK]\r\n");}catch (Exception){txtShowRecive.AppendText(GetBufferFormatHex(SendDataBytsBuffer) + "[Error]\r\n");}finally{txtShowRecive.AppendText("\r\n");}}}else{CloseSendData();btnSendData.Text = "发送数据";}}/// <summary>/// 结束发送线程/// </summary>private void CloseSendData(){IsLoopSendData = false;if (ThreadSendData != null && ThreadSendData.IsAlive){ThreadSendData.Abort();}}/// <summary>/// 定时发送数据/// </summary>void ProcSendData(){while (IsLoopSendData){if (EntitySerial != null && EntitySerial.IsOpen){EntitySerial.Write(SendDataBytsBuffer, 0, SendDataBytsBuffer.Length);SendBytesNu += SendDataBytsBuffer.Length;SendPacketNu++;Context.Post(ret => { labSendInfo.Text = SendPacketNu + "/" + SendBytesNu; }, null);}Thread.Sleep(SleepTiming);}}//16进制字符串得到byte[]private byte[] GetByteByHexString(string hexComTxt){hexComTxt = hexComTxt.Replace(" ", "").Replace("\r\n", "").Replace("\t", "");byte[] bytes = new byte[hexComTxt.Length / 2];for (int i = 0; i < bytes.Length; i++){bytes[i] = Convert.ToByte(hexComTxt.Substring(i * 2, 2), 16);}return bytes;}#endregionprivate void btnResate_Click(object sender, EventArgs e){SendPacketNu = 0;SendBytesNu = 0;Context.Post(ret => { labSendInfo.Text = "总包数/总字节数"; }, null);}private void txtShowRecive_DoubleClick(object sender, EventArgs e){((TextBox)sender).Text = "";}private void checkBoxRealShowInfo_CheckedChanged(object sender, EventArgs e){this.IsRealShowRecInfo = checkBoxRealShowInfo.Checked;}}class ReciveInfo{public byte[] Buffer { get; set; }public string TimerString { get; set; }}
}

嗯功能比较完整。有兴趣可以下载源码:https://download.csdn.net/download/weixin_43542114/12888689

C#网口通信和串口数据互相转发相关推荐

  1. C#松下PLC通信源代码,支持松下Mewtocol协议,支持网口通信和串口通信,部分代码稍作修改后可直接copy到自己的上位机软件使用

    C#松下PLC通信源代码,支持松下Mewtocol协议,支持网口通信和串口通信,部分代码稍作修改后可直接copy到自己的上位机软件使用 主要功能: 1.支持I/O实时监控,可自由改变要监控的I/O 2 ...

  2. 串口通信——接收串口数据并处理(C语言)

    本文主要内容包含:  1.接收串口数据程序的编程逻辑示意图:  2.接收串口数据程序要用到的通用函数模块(可直接引用,无需更改):  3.接收串口数据程序的示例. 1.接收串口数据程序的编程逻辑示意图 ...

  3. 串口通信与网口通信简介

    串口通信 串口通信介绍: 是指外设和计算机间,通过数据信号线 .地线.控制线等,按位进行传输数据的一种通讯方式. 这种通信方式使用的数据线少,在远距离通信中可以节约通信成本,但其传输速度比并行传输低. ...

  4. 昆仑通态串口定义_昆仑通态-嵌to嵌串口数据转发.pdf

    材料准备:两台TPC,一根串口对调线, 任务描述:在一定局域内建立本地与远程TPC通讯,本地转发,远程接收,并进 行测试. 串口连接 数据交换与控制 本地TPC7062K 远程TPC7062K 图6- ...

  5. linux mint wifi自动重试_涵盖物联网应用系统低成本WiFi通信模块:4GLTE转WiFi网口DTU串口数据透传APSTA模式等...

    大家好,我叫模小块,代号L107模块,出生在BOJINGnet大家庭里,我在物联网网关里不可或缺,或许业内专业人士和物联网工程师知道我的存在.别看我体积小(40mm25mm3mm),贴片式邮票孔接口( ...

  6. 读取串口数据_自定义串口通信的相关问题整理

    串口通信是常见的通信方式,串口接口是大部分工控器件标配的通信接口.在项目开发的过程中,也经常遇到进行串口通信的处理.这里就串口通信的部分问题分享给大家. 1.TTL.RS232.RS422.RS458 ...

  7. python串口通信_python 读取串口数据的示例

    python3 读取串口数据 demo 最近在写一个demo,zigbee串口连接树莓派,树莓派使用串口通信接受zigbee穿过来得值.其中我是用的树莓派是3代B+,zigbee每隔三秒钟从串口输出数 ...

  8. FPGA串口收发(四):接收数据并转发,间隔时间发送

    FPGA串口收发(四):接收数据并转发,间隔时间发送 // Description: 串口收发:串口接收数据,内部生成数据,串口间隔特定时间发送数据 // 串口接收数据:串行信号线 1101_1000 ...

  9. Android MCU之间的串口通信(收发数据)

    最近一个项目是android和MCU之间的串口指令数据通信,捣鼓了很久,也找了很多网上的资料.最后将实现的总结记录下来. 使用的是GitHub中的一个项目,下载地址:https://github.co ...

最新文章

  1. 腾讯优图8篇论文入选ECCV 2020,涵盖目标检测/跟踪/Re-ID/人脸等领域
  2. CVPR 9999 Best Paper:一种加辣椒的番茄炒蛋
  3. Android .9.png图片的处理
  4. android系统里面的mic是哪个app_苹果记事app哪个好用?这款便签可以跨系统使用...
  5. ElasticSearch技术文档
  6. openresty 前端开发入门四之Redis篇
  7. POI文件导入:需求说明
  8. PHPcurl抓取AJAX异步内容(转载)
  9. UIKit框架之NSObject
  10. 如何保留小数点后任意一位数
  11. 退休后多长时间能领到工资?
  12. 4——编码规则以及vim的使用和虚拟环境
  13. Android UI开发:AlertDialog对话框
  14. noob的第一步——基于51单片机的指纹密码锁
  15. android 支付宝 授权登录,android 支付宝授权登录、获取个人信息一键接入
  16. 2022年HELIUM3将引领链游开启gaming2.0时代
  17. 2019CVPR单目深度估计综述
  18. C++ 程序设计 week5 魔兽世界二: 装备
  19. 苹果iOS App上架流程,非iOS开发人员上架教程
  20. 【C++自学笔记 提高编程篇(二)STL初识】

热门文章

  1. 专业摄录像机的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告
  2. 乐视三合一体感摄像头Astra pro开发记录1(深度图、彩色图及点云简单显示)
  3. Web三维可视化监控系统搭建(2)——VR场景显示和交互
  4. 工具及方法 - 电子烟开发中使用温度测试工具
  5. 分割(计数板)展示数字样式
  6. Windows 7 开机自动拨号 常用的五种方法
  7. 杭电 Prime Ring Problem
  8. WIN10系统打不开局域网共享
  9. 小程序对火锅店的发展利好及部分可行性内容设计
  10. 秒杀系统防止超卖解决方案