C# DotNetty客户端

1. 引入DotNetty包

我用的开发工具是VS2022,不同工具引入可能会有差异

工具------>NuGet包管理器------>管理解决方案的NuGet程序包

搜索DotNetty

2.新建EchoClientHandler.cs类

用于接收服务器返回数据

复制代码
public class EchoClientHandler : SimpleChannelInboundHandler<IByteBuffer>
{
    /// <summary>
    /// Read0是DotNetty特有的对于Read方法的封装
    /// 封装实现了:
    /// 1. 返回的message的泛型实现
    /// 2. 丢弃非该指定泛型的信息
    /// </summary>
    /// <param name="ctx"></param>
    /// <param name="msg"></param>
    protected override void ChannelRead0(IChannelHandlerContext ctx, IByteBuffer msg)
    {
        if (msg != null)
        {
            Console.WriteLine("Receive From Server:" + msg.ToString(Encoding.UTF8));
        }
        //ctx.WriteAsync(Unpooled.CopiedBuffer(msg));
    }
    public override void ChannelReadComplete(IChannelHandlerContext context)
    {
        context.Flush();
    }
    public override void ChannelActive(IChannelHandlerContext context)
    {
        Console.WriteLine("==================ChannelActive======================");
        //context.WriteAndFlushAsync(Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes("Hello World!")));
    }

    public override void ChannelInactive(IChannelHandlerContext context)
    {
        Console.WriteLine("===============ChannelInactive==============");
        base.ChannelInactive(context);
        context.CloseAsync();
    }

    public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
    {
        Console.WriteLine("===============ExceptionCaught==============");
        Console.WriteLine(exception);
        context.CloseAsync();
    }
}

3.新建DotNettyClient.cs客户端类

复制代码
public class DotNettyClient
{
    private MultithreadEventLoopGroup group;
    private Bootstrap bootstrap;
    private IChannel channel;

    public async Task StartAsync()
    {
        group = new MultithreadEventLoopGroup();
        
        try
        {
            bootstrap = new Bootstrap()
                .Group(group)
                .Channel<TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new StringDecoder(Encoding.UTF8));
                    pipeline.AddLast(new StringEncoder(Encoding.UTF8));
                    pipeline.AddLast(new IdleStateHandler(0, 0, 600));
                    pipeline.AddLast(new EchoClientHandler());
                }));
            
            channel = await bootstrap.ConnectAsync("127.0.0.1", 9997);

            //byte[] bytes = Encoding.UTF8.GetBytes("aaaaa");
            //await channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(bytes));

            Console.WriteLine("Connected to server.");

            // 发送消息给服务器
            SendMessage("我是客户端");
            
            //关闭客户端连接
            //await channel.CloseAsync();
            //Console.WriteLine("Client connection closed.");
        }
        catch (Exception ex) { 
            Console.WriteLine(ex.ToString());
            Console.WriteLine(ex.StackTrace);
        }
        finally
        {
            await group.ShutdownGracefullyAsync();
        }
    }

    public void SendMessage(string message)
    {
        if (channel != null && channel.Open)
        {
            Console.WriteLine("666666666666666666666666666");
            channel.WriteAndFlushAsync(message);
            Console.WriteLine("Sent message to server: " + message);
        }
    }
}

4.使用DotNetty

我这里是窗体应用程序

复制代码
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        startClient();
    }

    public async Task startClient() {
        DotNettyClient client = new DotNettyClient();
        await client.StartAsync();//连接服务

        //client.SendMessage("111111111111111");
    }
}
相关推荐
love530love3 分钟前
命令行创建 UV 环境及本地化实战演示—— 基于《Python 多版本与开发环境治理架构设计》的最佳实践
开发语言·人工智能·windows·python·conda·uv
工藤新一OL7 分钟前
把xml的格式从utf-8-bom转为utf-8
xml·c#·asp.net·.netcore·visual studio
陪我一起学编程25 分钟前
MySQL创建普通用户并为其分配相关权限的操作步骤
开发语言·数据库·后端·mysql·oracle
麦子邪27 分钟前
C语言中奇技淫巧04-仅对指定函数启用编译优化
linux·c语言·开发语言
破刺不会编程1 小时前
linux线程概念和控制
linux·运维·服务器·开发语言·c++
henreash1 小时前
NLua和C#交互
开发语言·c#·交互
萌新小白的逆袭2 小时前
《Maven 核心基础笔记(第一天)》
java·开发语言·spring
苦学编程的谢2 小时前
MyBatis_3
java·开发语言·后端·mybatis
go54631584653 小时前
Python点阵字生成与优化:从基础实现到高级渲染技术
开发语言·人工智能·python·深度学习·分类·数据挖掘
猫头虎3 小时前
2025年02月11日 Go生态洞察:Go 1.24 发布亮点全面剖析
开发语言·后端·python·golang·go·beego·go1.19