文章目录
- .Net网络通信组件 - TouchSocket
- 1、新建.Net8控制台项目
- 2、Nuget安装TouchSocket组件
- 3、编写服务端代码
- 4、编写客户端代码
- 5、编写Program代码
- 6、运行效果
- 7、日志组件(NLog)参考我的另一篇博客
.Net网络通信组件 - TouchSocket
1、新建.Net8控制台项目
2、Nuget安装TouchSocket组件
install-package TouchSocket
3、编写服务端代码
using System.Text;
using TestTouchSocketApp.TouchSockets.Dtos;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace TestTouchSocketApp.TouchSockets
{
public class TestTouchSocketServer
{
public TestTouchSocketServer()
{
//初始化服务端
InitServer();
}
public TcpService TcpService { get; set; }
public List<TouchSocketClientDto> Clients { get; set; }
/// <summary>
/// 初始化服务端
/// </summary>
private void InitServer()
{
//初始化
TcpService = new TcpService();
//初始化
Clients = new();
TcpService.Connecting += (client, e) =>
{
//返回
return EasyTask.CompletedTask;
};
TcpService.Connected += (client, e) =>
{
//初始化
TouchSocketClientDto clientDto = new();
//赋值
clientDto.Index = Clients.Count + 1;
clientDto.ClientId = client.Id;
clientDto.Host = client.IP;
clientDto.Port = client.Port;
clientDto.Online = true;
clientDto.ConnectTime = DateTime.Now;
//添加
Clients.Add(clientDto);
//记录日志
LingbugLogUtil.Info($"有新客户端上线啦:{TouchSocketClientDto.GetContentStr(clientDto)}");
//返回
return EasyTask.CompletedTask;
};
TcpService.Received += (client, e) =>
{
try
{
//读取
var bytes = e.ByteBlock.ToArray();
//读取
var clientMsg = Encoding.UTF8.GetString(bytes);
//log
string log = $"Server Received,收到客户端发送的消息:【{clientMsg}】";
//记录日志
LingbugLogUtil.Info(log);
}
catch (Exception exception)
{
//记录日志
LingbugLogUtil.Error($"Server Received,读取客户端消息异常:{exception.Message}", exception);
}
//返回
return EasyTask.CompletedTask;
};
TcpService.Closing += (client, e) =>
{
//返回
return EasyTask.CompletedTask;
};
TcpService.Closed += (client, e) =>
{
foreach (var clientDto in Clients.FindAll(r => r.ClientId == client.Id))
{
//赋值
clientDto.Online = false;
clientDto.DisConnectTime = DateTime.Now;
//记录日志
LingbugLogUtil.Info($"客户端已下线:{TouchSocketClientDto.GetContentStr(clientDto)}");
}
//返回
return EasyTask.CompletedTask;
};
//初始化
var config = new TouchSocketConfig();
//赋值
config.SetListenIPHosts(new IPHost[] { "127.0.0.1:9990", "127.0.0.1:9991" });
config.SetMaxCount(100);
config.SetThreadCount(10);
//配置
TcpService.Setup(config);
//启动
TcpService.Start();
//打印
LingbugLogUtil.Info("server is started,listening on 127.0.0.1:9990,127.0.0.1:9991");
}
/// <summary>
/// 获取在线客户端
/// </summary>
/// <returns></returns>
public List<TouchSocketClientDto> GetConnectedClients()
{
//数据
var clients = Clients ?? new();
//过滤
return clients.FindAll(r => r.Online);
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="clientId"></param>
/// <param name="msg"></param>
public void SendMsg(string clientId, string msg)
{
//发送消息
TcpService.Send(clientId, msg);
}
}
}
4、编写客户端代码
using System.Text;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace TestTouchSocketApp.TouchSockets
{
public class TestTouchSocketClient
{
public TestTouchSocketClient(string listenServer)
{
//初始化客户端
InitClient(listenServer);
}
public TcpClient TcpClient { get; set; }
/// <summary>
/// 初始化客户端
/// </summary>
/// <param name="listenServer"></param>
private void InitClient(string listenServer)
{
//初始化
TcpClient = new TcpClient();
TcpClient.Connecting += (client, e) =>
{
//返回
return EasyTask.CompletedTask;
};
TcpClient.Connected += (client, e) =>
{
//返回
return EasyTask.CompletedTask;
};
TcpClient.Received += (client, e) =>
{
try
{
//读取
var bytes = e.ByteBlock.ToArray();
//读取
var serverMsg = Encoding.UTF8.GetString(bytes);
//log
string log = $"Client Received,收到服务器发送的消息:【{serverMsg}】";
//记录日志
LingbugLogUtil.Info(log);
}
catch (Exception exception)
{
//记录日志
LingbugLogUtil.Error($"Client Received,读取服务器消息异常:{exception.Message}", exception);
}
//返回
return EasyTask.CompletedTask;
};
TcpClient.Closing += (client, e) =>
{
//返回
return EasyTask.CompletedTask;
};
TcpClient.Closed += (client, e) =>
{
//返回
return EasyTask.CompletedTask;
};
//初始化
var config = new TouchSocketConfig();
//赋值
config.SetRemoteIPHost(new IPHost(listenServer));
//配置
TcpClient.Setup(config);
//启动
TcpClient.Connect();
//打印
LingbugLogUtil.Info($"client is connected to server,server is {listenServer}");
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="msg"></param>
public void SendMsg(string msg)
{
//发送消息
TcpClient.Send(msg);
}
}
}
5、编写Program代码
using TestTouchSocketApp.TouchSockets;
using TestTouchSocketApp.TouchSockets.Dtos;
namespace TestTouchSocketApp
{
internal class Program
{
static void Main(string[] args)
{
try
{
//打印
Console.WriteLine("请输入,1:服务端;2:客户端;");
//读取
var input = Console.ReadLine();
if (input == "1")
{
//初始化
TestTouchSocketServer server = new();
//打印
Console.WriteLine("请输入要发送给客户端的消息:");
//读取
var msg = Console.ReadLine();
//打印
Console.WriteLine("要发送给哪个客户端,当前连接的客户端有:");
//获取在线客户端
var clients = server.GetConnectedClients();
foreach (var client in clients)
{
//打印
Console.WriteLine(TouchSocketClientDto.GetContentStr(client));
}
//读取
var clientId = Console.ReadLine();
//发送消息
server.SendMsg(clientId, msg);
}
else if (input == "2")
{
//打印
Console.WriteLine("请输入要连接的服务端地址:");
//读取
var server = Console.ReadLine();
//初始化
TestTouchSocketClient client = new(server);
//打印
Console.WriteLine("请输入要发送给服务器的消息:");
//读取
var msg = Console.ReadLine();
//发送消息
client.SendMsg(msg);
}
}
catch (Exception e)
{
//记录日志
LingbugLogUtil.Error($"程序异常:{e.Message}", e);
}
//读取
Console.ReadKey();
}
}
}
6、运行效果
7、日志组件(NLog)参考我的另一篇博客
.Net日志组件之NLog的使用和配置