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();

最低0.47元/天 解锁文章
930

被折叠的 条评论
为什么被折叠?



