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.xx.xx";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}");}}
}
在上面的代码中,message.GetBytes("GBK") 是插件作者封装的拓展方法,如下
public static byte[] GetBytes(this string str, string encodeName = "UTF-8")
{return Encoding.GetEncoding(encodeName).GetBytes(str);
}
可以看到,这里用的 Encoding.GetEncoding(encodeName) 去获取 Encoding 编码格式
常见的编码格式有:
utf-8
us-ascii
windows-1252
iso-8859-1
gb2312
gbk
big5
shift_jis
Euc-kr
用法:
Encoding encoding = Encoding.GetEncoding("gb2312");
也可以使用下面代码来查看有那些编码格式
foreach (EncodingInfo encInfo in Encoding.GetEncodings())
{Console.WriteLine($"{encInfo.CodePage} - {encInfo.Name}");
}
end