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

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

背景

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

工具

串口调试助手

网络调试助手

代码

客户端

cs 复制代码
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";
        }

    }
}

服务端

cs 复制代码
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();
            }

        }
    }
}

串口

cs 复制代码
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;
            }
        }
    }
}

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

相关推荐
Eiceblue12 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
IUGEI12 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
czhc114007566314 小时前
C# 1124 接收
开发语言·c#
时光追逐者16 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 62 期(2025年11.17-11.23)
c#·.net·.netcore
司铭鸿16 小时前
祖先关系的数学重构:从家谱到算法的思维跃迁
开发语言·数据结构·人工智能·算法·重构·c#·哈希算法
s090713617 小时前
ZYNQ DMA to UDP 数据传输系统设计文档
网络协议·fpga开发·udp
宝桥南山19 小时前
.NET 10 - Blazor web assembly应用的一些诊断方式
microsoft·微软·c#·asp.net·.net·.netcore
百***060120 小时前
【Golang】——Gin 框架中的表单处理与数据绑定
microsoft·golang·gin
hazy1k20 小时前
ESP32基础-Socket通信 (TCP/UDP)
c语言·单片机·嵌入式硬件·网络协议·tcp/ip·udp·esp32
xinxinhenmeihao20 小时前
爬虫为什么要用动态ip?动态IP在爬虫中起到哪些作用?
爬虫·网络协议·tcp/ip