欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > SerialportToTCP② 全

SerialportToTCP② 全

2024/10/25 4:14:56 来源:https://blog.csdn.net/weixin_73535261/article/details/140161501  浏览:    关键词:SerialportToTCP② 全

效果补全(代码):

namespace SerialportToTCP
{public partial class Form1 : Form{IniHelper Ini;string[] botelvs = new string[] { "1200", "4800", "9600", "13200" };public Form1(){InitializeComponent();//1 读取配置文件string dirPath = Path.Combine(Application.StartupPath, "File");// debug/filestring filePath = Path.Combine(dirPath, "Setting.ini");// debug / file/setting.iniIni = new IniHelper(filePath); //创建读取对象// 添加串口comboBox1.Items.AddRange(SerialPort.GetPortNames());// 获取所有串口 拼接在下拉框的items中comboBox2.Items.AddRange(botelvs);// 添加波特率数组comboBox2.Items.Add("自定义");//添加一个comboBox3.Items.AddRange(new string[] { "5", "6", "7", "8" });comboBox4.Items.AddRange(new string[] { "无", "奇校检", "偶校检" });comboBox5.Items.AddRange(new string[] { "无", "1", "2", "1.5" });//2开始处理串口接受数据事件//处理串口的数据this.serialPort1.DataReceived += SerialPort1_DataReceived;//3 处理界面显示默认值 也就是从ini文件读取数据readSetting();//4 开始串口通信startChuanKou();//5 开始网口通信startTCP();}//开始搭建TCP服务器TcpListener listen;List<TcpClient> lists = new List<TcpClient>();//存放所有的客户端void startTCP(){if(!int.TryParse(textBox3.Text,out int port) || port < 1 || port >65563){MessageBox.Show("请输入正确的端口号");}//开启服务器 接受客户端try{listen = new TcpListener(System.Net.IPAddress.Any, port);listen.Start(100); //开始监听panel2.BackColor = Color.Green;//把多个客户端接受到数组里面 异步接受new Task(() => {try{while (true){//接收客户端TcpClient c1 = listen.AcceptTcpClient();// 把客户端添加到数组里面 群发需要lists.Add(c1);//接收客户端发来的消息tcpReceive(c1);}}catch{MessageBox.Show("TCP服务器关闭");}}).Start();}catch{MessageBox.Show("TCP启动失败");//把tcp关闭等操作foreach (var item in lists){item.Close(); //关闭所有的客户端}listen.Stop();panel2.BackColor = Color.Gray;}}//tcp 接收数据void tcpReceive(TcpClient c1){new Task(() =>{NetworkStream stream = c1.GetStream();try{while (c1.Connected) //客户端连接的时候{byte[] bs = new byte[1024];int length =  stream.Read(bs, 0, bs.Length);if (length == 0) throw new Exception(); // 客户端断了//接收到数据亮灯tcpLiangDeng();//把数据转给串口if (!serialPort1.IsOpen){MessageBox.Show("串口关闭");break;}//把数据转给串口 serialPort1发送数据, com6能接受到消息,serialPort1.Write(bs, 0, length);}}catch{c1.Close();lists.Remove(c1);}}).Start();}//tcp 接收到数据亮灯的方法async void tcpLiangDeng(){this.Invoke((Action)(() =>{textBox2.Text = (int.Parse(textBox2.Text) + 1).ToString();//亮灯panel4.BackColor = Color.Green;}));//过一段时间await Task.Delay(70);this.Invoke((Action)(() =>{//关灯panel4.BackColor = Color.Gray;}));}void startChuanKou(){// 配置串口对象try{this.serialPort1.PortName = comboBox1.Text;//配置串口名称this.serialPort1.BaudRate = int.Parse(comboBox2.Text); //波特率this.serialPort1.DataBits = int.Parse( comboBox3.Text);this.serialPort1.StopBits = (StopBits)comboBox5.SelectedIndex;// 正常赋值 StopBits.None 枚举值。正好对应数据0this.serialPort1.Parity = (Parity)comboBox4.SelectedIndex; // this.serialPort1.Open();//亮灯this.panel1.BackColor = Color.Green;}catch{MessageBox.Show("打开串口失败");//停止串口if(serialPort1.IsOpen) serialPort1.Close();//灭灯this.panel1.BackColor = Color.Gray;}}void readSetting(){//先配置串口comboBox1.SelectedItem = Ini.Read("Serialport", "name", "");string botelv = Ini.Read("Serialport", "botelv", "9601");int botelvIndex = Array.IndexOf(botelvs, botelv);// 获取botelv在数组里面的索引值if (botelvIndex != -1) // 证明波特率在数组里面{comboBox2.SelectedIndex= botelvIndex;comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;}else{//波特率在数组里面 自定义波特率情况comboBox2.DropDownStyle = ComboBoxStyle.DropDown; //可编辑的下拉框//DropDownList 不可编辑的下拉框comboBox2.Text = botelv;}//处理数据位comboBox3.SelectedItem = Ini.Read("Serialport", "databit", "8");//处理奇偶校检comboBox4.SelectedIndex = Ini.Read("Serialport", "parity", 0);comboBox5.SelectedIndex = Ini.Read("Serialport", "stopbit", 0);comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;comboBox3.DropDownStyle = ComboBoxStyle.DropDownList;comboBox4.DropDownStyle = ComboBoxStyle.DropDownList;comboBox5.DropDownStyle = ComboBoxStyle.DropDownList;//网口数据的读取textBox3.Text = Ini.Read("NetWork", "port", "8080");if( Ini.Read("NetWork", "heartOn", false)){radioButton1.Checked = true;}else{radioButton2.Checked = true;}textBox4.Text= Ini.Read("NetWork", "heartTime", "60000");// 心跳间隔  textBox5.Text = Ini.Read("NetWork", "heartData", ""); //心跳包数据checkBox1.Checked = Ini.Read("NetWork", "heartHex", false);//s是否采用16进制}// 接受串口传递数据private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e){byte[] bs = new byte[1024]; //定义一个字节数组int count = serialPort1.Read(bs, 0, bs.Length); //读取数据到字节数组里面if (count == 0){//关闭串口//停止串口if (serialPort1.IsOpen) serialPort1.Close();//灭灯this.panel1.BackColor = Color.Gray;}//1 接收到1条串口数据 需要panel3亮一次 封装一个方法控制效果jieShouDaoChuankou();//2 转发给所有客户端数据 串口转网口就是把串口数据通过网络转给其他客户端 foreach (var item in lists){item.GetStream().Write(bs, 0, bs.Length);}}async void jieShouDaoChuankou(){this.Invoke((Action)(() =>{textBox1.Text = (int.Parse(textBox1.Text)+1).ToString();//亮灯panel3.BackColor = Color.Green;}));//过一段时间await Task.Delay(70);this.Invoke((Action)(() =>{//关灯panel3.BackColor = Color.Gray;}));}//波特率下拉框触发变化的时候调用private void comboBox2_SelectedIndexChanged(object sender, EventArgs e){if (comboBox2.SelectedItem.ToString() == "自定义"){//切换到自定义选项上comboBox2.DropDownStyle= ComboBoxStyle.DropDown;}else{comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;}}//选中心跳开关为开的时候private void radioButton1_CheckedChanged(object sender, EventArgs e){//MessageBox.Show(textBox4.Text + "????/");if (radioButton1.Checked){//选中心跳timer1.Interval = string.IsNullOrEmpty(textBox4.Text) ? 2000 : int.Parse(textBox4.Text); timer1.Tick += Timer1_Tick;timer1.Start();}}//定时器函数private void Timer1_Tick(object sender, EventArgs e){//定时发送数据string data = textBox5.Text; //心跳数据 2选中hex证明把2转成16进制,byte[] buffer;if (checkBox1.Checked == true){//需要发16进制的心跳string[] ds = data.Split(' '); //把2按照空格符号分割成数组结构[2]buffer = new byte[ds.Length]; //buffer数组长度就是ds的长度for (int i = 0; i < ds.Length; i++){//System.Globalization.NumberStyles.HexNumber 转成16进制数//把ds[i]转成16进制buffer[i] = byte.Parse(ds[i], System.Globalization.NumberStyles.HexNumber);}}else{//不采用16进制的心跳包buffer = Encoding.UTF8.GetBytes(data);}foreach (var item in lists){item.GetStream().Write(buffer, 0, buffer.Length);}}//关闭心跳private void radioButton2_CheckedChanged(object sender, EventArgs e){timer1.Stop();}//重启private void button1_Click(object sender, EventArgs e){//停掉tcpforeach (var item in lists){item.Close(); //关闭所有的客户端}listen.Stop();panel2.BackColor = Color.Gray;//停掉串口if (serialPort1.IsOpen) serialPort1.Close();//灭灯this.panel1.BackColor = Color.Gray;//开启tcpstartTCP();//开启串口startChuanKou();}//保存private void button2_Click(object sender, EventArgs e){//Serialport", "databit", "8");Ini.Write("Serialport", "name", comboBox1.Text);Ini.Write("Serialport", "botelv", comboBox2.Text);Ini.Write("Serialport", "stopbit", comboBox5.SelectedIndex);Ini.Write("Serialport", "parity", comboBox4.SelectedIndex);Ini.Write("Serialport", "databit", comboBox3.Text);//5 6 7 8 Ini.Write("NetWork", "port", textBox3.Text);Ini.Write("NetWork", "heartOn",radioButton1.Checked);Ini.Write("NetWork", "heartTime", textBox4.Text);Ini.Write("NetWork", "heartData", textBox5.Text);Ini.Write("NetWork", "heartHex", checkBox1.Checked);}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com