.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的使用和配置

相关推荐
likfishdn8 分钟前
Linux的文件与目录管理
linux·运维·服务器
渲染101专业云渲染10 分钟前
川翔云电脑优势总结
服务器·3d·电脑·blender·maya
chian-ocean28 分钟前
Linux 文件缓冲区:高效数据访问的幕后推手
linux·运维·服务器
加油=^_^=30 分钟前
【Linux】进程优先级 | 进程调度(三)
linux·运维·服务器
橘子味的茶二39 分钟前
高级系统架构师--第十章:计算机网络
服务器·计算机网络·系统架构
紫菜(Nori)1 小时前
短连接服务器压测-wrk
服务器·压力测试
陆沙1 小时前
deepseek-r1-centos-本地服务器配置方法
linux·服务器·centos
吃汤圆的抹香鲸2 小时前
Rider 安装包 绿色版 Win/Mac/Linux 适合.NET和游戏开发者使用 2025全栈开发终极指南:从零配置到企业级实战
linux·运维·windows·sql·游戏·macos·.net
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#