C# DotNetty客户端

13,332次阅读
没有评论

共计 2666 个字符,预计需要花费 7 分钟才能阅读完成。

1. 引入 DotNetty 包

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

工具——>NuGet 包管理器——> 管理解决方案的 NuGet 程序包
C# DotNetty 客户端
搜索 DotNetty
C# DotNetty 客户端

2. 新建 EchoClientHandler.cs 类

用于接收服务器返回数据

public class EchoClientHandler : SimpleChannelInboundHandler
{/// 
    /// Read0 是 DotNetty 特有的对于 Read 方法的封装
    /// 封装实现了:/// 1. 返回的 message 的泛型实现
    /// 2. 丢弃非该指定泛型的信息
    /// 
    /// 
    /// 
    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()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer(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");
    }
}

原文地址: C# DotNetty 客户端

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-09-30发表,共计2666字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)