TcpClient 自己封装的话,还是比较麻烦的,可以基于线程,也可以基于异步写,最好的办法是网上找个插件,我发现一个插件还是非常好用的:STTech.BytesIO.Tcp
下面是这个插件作者的帖子,有兴趣的可以去看看
TcpClient
BytesIO | 零基础轻松看懂 C# TCP客户端(完整源码+视频教程)_sttech.bytesio.tcp-CSDN博客
TcpServer
BytesIO | C# 超简洁的TCP服务端开发(完整源码+视频教程)_c# bytesio-CSDN博客
目前网上大部分帖子都是用 PropertyGrid 控件去实现的,其实没必要
我做了一个简单的界面,如下
代码:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TcpClinetTest2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
STTech.BytesIO.Tcp.TcpClient tcpClient;
private void Form1_Load(object sender, EventArgs e)
{
this.tcpClient = new STTech.BytesIO.Tcp.TcpClient();
//tcp接收数据时触发的事件
this.tcpClient.OnDataReceived += TcpClient_OnDataReceived;
//tcp连接成功时触发的事件
this.tcpClient.OnConnectedSuccessfully += TcpClient_OnConnectedSuccessfully;
//tcp连接断开时触发的事件
this.tcpClient.OnDisconnected += TcpClient_OnDisconnected;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.tcpClient.IsConnected)
this.tcpClient.Disconnect();
}
private void TcpClient_OnDisconnected(object sender, STTech.BytesIO.Core.DisconnectedEventArgs e)
{
Console.WriteLine($"已断开:{e.ReasonCode}");
}
private void TcpClient_OnConnectedSuccessfully(object sender, STTech.BytesIO.Core.ConnectedSuccessfullyEventArgs e)
{
Console.WriteLine("连接成功");
}
private void TcpClient_OnDataReceived(object sender, STTech.BytesIO.Core.DataReceivedEventArgs e)
{
Console.WriteLine($"收到数据:{e.Data.EncodeToString("GBK")}");
}
//连接
private void Button_Connect_Click(object sender, EventArgs e)
{
this.tcpClient.Host = "192.168.30.91";
this.tcpClient.Port = 6666;
var result = this.tcpClient.Connect();
Console.WriteLine($"结果:{result.IsSuccess},错误码:{result.ErrorCode}");
}
//断开
private void Button_Disconnect_Click(object sender, EventArgs e)
{
this.tcpClient?.Disconnect();
}
//发送
private void Button_Send_Click(object sender, EventArgs e)
{
string message = TextBox_Message.Text;
if (string.IsNullOrEmpty(message))
{
Console.WriteLine("消息框为空");
return;
}
this.tcpClient.Send(message.GetBytes("GBK"));
}
//清空控制台
private void Button_ClearConsole_Click(object sender, EventArgs e)
{
Console.Clear();
}
//获取在线状态
private void Button_GetOnlineStatus_Click(object sender, EventArgs e)
{
Console.WriteLine($"在线状态:{this.tcpClient.IsConnected}");
}
}
}
end