C# 串口与TCP客户端 STTech.BytesIO

程序路径:
链接:https://pan.baidu.com/s/1iQoHQHjEdLXxMdmg3LOFMg
提取码:qdn2

具体代码

using STTech.BytesIO.Core;
using STTech.BytesIO.Serial;
using STTech.BytesIO.Tcp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CommInterface
{
    public partial class Form1 : Form
    {
        // NuGet 安装 STTech.BytesIO.Tcp 
        // 创建TCP客户端对象
        private BytesClient client;

        public Form1()
        {

            // 中文编码
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;

            // 初始化 客户端
            client = new TcpClient() { Port = 60000 };
            //client = new SerialClient();

            // 添加 接受数据 事件
            this.client.OnDataReceived += Client_OnDataReceived;
            // 添加 连接成功 事件
            this.client.OnConnectedSuccessfully += Client_OnConnectedSuccessfully;
            // 添加 断开连接 事件
            this.client.OnDisconnected += Client_OnDisconnected;

            // 客户端属性修改
            propertyGrid1.SelectedObject = client;
        }

        // 断开连接
        private void Client_OnDisconnected(object sender, STTech.BytesIO.Core.Entity.DisconnectedEventArgs e)
        {
            Print($"已断开 {e.ReasonCode}");
        }

        // 连接成功
        private void Client_OnConnectedSuccessfully(object sender, STTech.BytesIO.Core.Entity.ConnectedSuccessfullyEventArgs e)
        {
            Print("连接成功!");
        }

        // 接受数据
        private void Client_OnDataReceived(object sender, STTech.BytesIO.Core.Entity.DataReceivedEventArgs e)
        {
            Print("收到数据:" + e.Data.EncodeToString("GBK"));
        }

        // 断开链接
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            this.client.Disconnect();
        }

        // 链接
        private void btnConnect_Click(object sender, EventArgs e)
        {
            this.client.Connect();
        }

        // 发送消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            // 发送消息
            // Install-Package System.Text.Encoding.CodePages
            this.client.Send(this.tbSend.Text.GetBytes("GBK"));
            Print("发送数据:" + this.tbSend.Text);
        }

        private void Print(string msg)
        {
            tbRecv.AppendText($"[{DateTime.Now}] {msg}\r\n");
        }

    }
}


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廷益--飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值