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

相关推荐
lihuhelihu27 分钟前
第3章 CentOS系统管理
linux·运维·服务器·计算机网络·ubuntu·centos·云计算
山东布谷科技官方1 小时前
布谷直播源码部署服务器关于数据库配置的详细说明
运维·服务器·数据库·直播系统源码·直播源码·直播系统搭建·直播软件开发
爱吃喵的鲤鱼1 小时前
linux进程的状态之环境变量
linux·运维·服务器·开发语言·c++
小码编匠2 小时前
一款 C# 编写的神经网络计算图框架
后端·神经网络·c#
荒Huang2 小时前
Linux挖矿病毒(kswapd0进程使cpu爆满)
linux·运维·服务器
九河云3 小时前
如何选择适合的AWS EC2实例类型
服务器·云计算·aws
其乐无涯4 小时前
服务器技术(一)--Linux基础入门
linux·运维·服务器
写bug的小屁孩4 小时前
前后端交互接口(三)
运维·服务器·数据库·windows·用户界面·qt6.3
斑布斑布4 小时前
【linux学习2】linux基本命令行操作总结
linux·运维·服务器·学习
紅色彼岸花4 小时前
第六章:DNS域名解析服务器
运维·服务器