Winform上位机TCP客户端/服务端、串口通信

ops/2024/10/18 5:52:26/

Winform上位机TCP客户端/服务端、串口通信

背景

日常练习,着急换工作,心态都快乱了。

工具

串口调试助手

网络调试助手

代码

客户端

using Microsoft.VisualBasic.Logging;
using System.Net.Sockets;
using System.Text;namespace TcpClientDemo
{public partial class Form1 : Form{public Form1(){InitializeComponent();}TcpClient tcpClient = new TcpClient();/// <summary>/// 连接服务端/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void connect_Click(object sender, EventArgs e){if (!tcpClient.Connected){tcpClient.Connect(IP.Text, int.Parse(PORT.Text));//开启线程一直读取数据Task.Run(() =>{while (true){NetworkStream networkStream = tcpClient.GetStream();if (networkStream != null){byte[] datas = new byte[1024];networkStream.Read(datas, 0, datas.Length);this.BeginInvoke(new Action(() =>{log.Text = Encoding.UTF8.GetString(datas);}));}}});}}/// <summary>/// 发送数据/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void send_Click(object sender, EventArgs e){NetworkStream networkStream = tcpClient.GetStream();if (networkStream != null){byte[] datas = Encoding.UTF8.GetBytes(log.Text);networkStream.Write(datas, 0, datas.Length);}}private void Form1_Load(object sender, EventArgs e){IP.Text = "127.0.0.1";PORT.Text = "8899";}}
}

服务端

using Microsoft.VisualBasic.Logging;
using System.Net;
using System.Net.Sockets;
using System.Text;namespace TcpSeverDemo
{public partial class Form1 : Form{public Form1(){InitializeComponent();}//监听类TcpListener listener = null;//客户端TcpClient handler = null;NetworkStream stream = null;bool isrun = false;/// <summary>/// 打开/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void openServer_Click(object sender, EventArgs e){if (IP.Text.Trim().Length < 9 && Port.Text.Trim().Length == 0){MessageBox.Show("IP和端口无效");return;}listener = new TcpListener(IPAddress.Parse(IP.Text), int.Parse(Port.Text));listener.Start();isrun = true;}private void send_Click(object sender, EventArgs e){if (stream != null){byte[] buffer = Encoding.UTF8.GetBytes(log.Text);//load已经连接,可以直接发送stream.Write(buffer, 0, buffer.Length);}}private void Form1_Load(object sender, EventArgs e){IP.Text = "127.0.0.1";Port.Text = "9800";try{Task.Run(() =>{while (true){if (isrun && listener != null){//用来接收handler = listener.AcceptTcpClient();//创建网络流 已经连接stream = handler.GetStream();byte[] buffer = new byte[1024];if (stream != null){stream.Read(buffer, 0, buffer.Length);this.BeginInvoke(new Action(() =>{log.Text = Encoding.UTF8.GetString(buffer);}));}}Thread.Sleep(50);}});}catch (Exception){}}/// <summary>/// 关闭/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Form1_FormClosing(object sender, FormClosingEventArgs e){isrun = false;if (listener != null){listener.Stop();}}}
}

串口

using Microsoft.VisualBasic.Logging;
using System.Data;
using System.IO.Ports;
using System.Text;namespace PortDemo
{public partial class Form1 : Form{public Form1(){InitializeComponent();}SerialPort serialPort = new SerialPort();private void open_Click(object sender, EventArgs e){try{if (!serialPort.IsOpen){serialPort.Open();serialPort.DataReceived += SerialPort_DataReceived;}}catch (Exception ex){log.Text = ex.Message;}}private void read_Click(object sender, EventArgs e){}private void write_Click(object sender, EventArgs e){serialPort.Write(log.Text);}private void Form1_Load(object sender, EventArgs e){//导入一些基础参数List<string> ports = SerialPort.GetPortNames().ToList();foreach (var item in ports){port.Items.Add(item);}List<int> baus = new List<int> { 9600, 115200 };foreach (var item in baus){bau.Items.Add(item);}List<int> databits = new List<int> { 6, 7, 8 };foreach (var item in databits){databit.Items.Add(item);}List<string> cks = new List<string> { "None" };foreach (var item in cks){check.Items.Add(item);}List<string> stops = new List<string> { "One" };foreach (var item in stops){stop.Items.Add(item);}try{serialPort.PortName = port.Text;serialPort.BaudRate = int.Parse(bau.Text);serialPort.Parity = Parity.None;serialPort.DataBits = int.Parse(databit.Text);serialPort.StopBits = StopBits.One;}catch (Exception ex){log.Text = ex.Message;}}private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e){byte[] bytes = new byte[1024];try{serialPort.Read(bytes, 0, bytes.Length);string data = Encoding.UTF8.GetString(bytes);this.Invoke(() =>{log.Text = data;});}catch (Exception ex){log.Text = ex.Message;}}}
}

Socket通信

using System;
using System.Net;
using System.Net.Sockets;class Program
{static void Main(){Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);listener.Bind(new IPEndPoint(IPAddress.Any, 13000));listener.Listen(10);while (true){Console.WriteLine("Waiting for a connection...");Socket handler = listener.Accept();Console.WriteLine("Connected!");// 处理连接HandleClient(handler);}}private static void HandleClient(Socket client){NetworkStream stream = new NetworkStream(client);byte[] data = new byte[256];while (true){int bytes = stream.Read(data, 0, data.Length);if (bytes == 0)break;string text = Encoding.ASCII.GetString(data, 0, bytes);Console.WriteLine("Received: {0}", text);}client.Close();}
}

最简单的调用,之后会补充实际细节。这种基本不需要自己手动造轮子,除非重新开发,基本都是封装好的,会调用就可以,需要自己写的时候网上找找一堆。


http://www.ppmy.cn/ops/84779.html

相关文章

Arraylist与LinkedList的区别

Arraylist 概念 Arraylist非线程安全Arraylist 底层使用的是Object数组ArrayList 采用数组存储&#xff0c;插入和删除元素的时间复杂度受元素位置的影响ArrayList 支持快速随机访问,就是通过元素的序号快速获取元素对象ArrayList的空间浪费主要体现在列表的结尾会预留一定的容…

springSecurity学习之springSecurity web如何取得用户信息

web如何取得用户信息 之前说过SecurityContextHolder默认使用的是ThreadLocal来进行存储的&#xff0c;而且每次都会清除&#xff0c;但是web每次请求都会验证用户权限&#xff0c;这是如何做到的呢&#xff1f; 这是通过SecurityContextPersistenceFilter来实现的&#xff0…

MySQL中,除了使用LIKE进行模糊搜索外,还有其他几种方法可以执行搜索操作

在PHP和MySQL中&#xff0c;除了使用LIKE进行模糊搜索外&#xff0c;还有其他几种方法可以执行搜索操作&#xff0c;具体使用哪种方法取决于你的具体需求&#xff08;如性能、精确度、查询的复杂性等&#xff09;。以下是一些常用的搜索方法&#xff1a; REGEXP 或 RLIKE&…

二阶段测试:

二阶段测试&#xff1a; 架构&#xff1a; 服务器类型部署组件ip地址DR1调度服务器 主&#xff08;ha01&#xff09;KeepalivedLVS-DR192.168.60.30DR2调度服务器 备 (ha02)KeepalivedLVS-DR192.168.60.40web1节点服务器 (slave01)NginxTomcatMySQL 备MHA managerMHA node192.…

后端返回列表中包含图片id,如何将列表中的图片id转化成url

问题描述 如果我有一个列表数据&#xff0c;列表中每个对象都包含一个图片id&#xff0c;现在我需要将列表中的图片id转化成图片&#xff0c;然后再页面上显示出来 如果你有一个列表数据&#xff0c;列表中每个对象都包含一个图片 ID&#xff0c;并且你想将这些图片 ID 转化为…

ffmpeg把pcm封装为wav

note 1.wav格式中&#xff0c;音频数据未经过压缩&#xff0c;直接封装即可 2.对于编码器的选择&#xff0c;应选择和pcm裸数据一致的编码器(本次实际不须编码) version #define LIBSWRESAMPLE_VERSION_MAJOR 2 #define LIBSWRESAMPLE_VERSION_MINOR 9 #define LIBSWRESAM…

【常见开源库的二次开发】基于openssl的加密与解密——SHA算法源码解析(六)

目录 一、SHA-1算法分析&#xff1a; 1.1 Merkle Tree可信树 1.2 源码实现&#xff1a; 1.3 哈希计算功能 1.4 两种算法的区别&#xff1a; 1.4.1 目的 1.4.2 实现机制 1.4.3 输出 1.4.4 应用场景&#xff1a; 1.4 运行演示&#xff1a; 二、SHA-2算法分析&#xff1a; 2.1哈…

在线教育数仓项目(数据采集部分1)

文章目录 数据仓库概念项目需求及架构设计项目需求分析系统数据流程设计框架版本选型集群规模估算集群资源规划设计 数据生成模块目标数据页面事件曝光启动播放错误 数据埋点主流埋点方式&#xff08;了解&#xff09;埋点数据上报时机埋点数据日志结构 服务器和JDK准备服务器准…