程序路径:
链接: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");
}
}
}