.Net网络通信组件 - TouchSocket

文章目录

.Net网络通信组件 - TouchSocket

1、新建.Net8控制台项目

2、Nuget安装TouchSocket组件

install-package TouchSocket

3、编写服务端代码

csharp 复制代码
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、编写客户端代码

csharp 复制代码
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代码

csharp 复制代码
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的使用和配置

相关推荐
Clownseven16 分钟前
Linux服务器健康检查Shell脚本:一键生成自动化巡检报告
linux·服务器·自动化
mysla1 小时前
嵌入式学习day34-网络-tcp/udp
服务器·网络·学习
格林威3 小时前
Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型和EasyOCR实现汽车牌照动态检测和识别(C#代码,UI界面版)
人工智能·深度学习·数码相机·yolo·c#·汽车·视觉检测
Aczone283 小时前
Linux 软件编程(九)网络编程:IP、端口与 UDP 套接字
linux·网络·网络协议·tcp/ip·http·c#
终端行者3 小时前
jenkins实现分布式构建并自动发布到远程服务器上 jenkins实现自动打包编译发布远程服务器
服务器·分布式·jenkins
不叫猫先生3 小时前
Amazon Lambda:无服务器时代的计算革命,解锁多样化应用场景
服务器·数据库·人工智能·amazon lambda
yuyuyui3 小时前
Abp vNnext-事件总线使用实现及解析
.net·abp vnext
秋天枫叶353 小时前
【AI应用】修改向量数据库Milvus默认密码
运维·服务器·数据库·ubuntu·milvus·milvus_cli
qq_411262424 小时前
为什么会“偶发 539/500 与建连失败”
服务器·c语言·网络·智能路由器
我科绝伦(Huanhuan Zhou)4 小时前
Linux服务器性能优化总结
linux·服务器·性能优化