C#使用Netty demo

这里写目录标题

一服务器

using System;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;

namespace Nettyfwq
{
    public class TcpServer
    {
        public async Task Start()
        {
            IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                ServerBootstrap bootstrap = new ServerBootstrap()
                    .Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Option(ChannelOption.SoBacklog, 100)
                    .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                        pipeline.AddLast(new StringDecoder(Encoding.UTF8));
                        pipeline.AddLast(new LengthFieldPrepender(4));
                        pipeline.AddLast(new StringEncoder(Encoding.UTF8));
                        pipeline.AddLast(new TcpServerHandler());
                    }));

                IChannel boundChannel = await bootstrap.BindAsync(8888);
                Console.WriteLine("TCP server started on port 8888. Press any key to exit.");
                Console.ReadKey();

                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
                );
            }
        }
    }

    public class TcpServerHandler : SimpleChannelInboundHandler<string>
    {
        protected override void ChannelRead0(IChannelHandlerContext context, string message)
        {
            Console.WriteLine($"Received data: {message}");

            // 在这里处理接收到的数据

            context.Channel.WriteAndFlushAsync("我是服务器");
        }

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

        public override void ChannelActive(IChannelHandlerContext context)
        {
            string clientName = context.Channel.RemoteAddress.ToString();

            // 打印客户端名称
            Console.WriteLine("连接到一台客户端:" + clientName);

            base.ChannelActive(context);
            Console.WriteLine("连接到一台客户端:" + clientName);
        }
    }

    public class Program
    {
        public static async Task Main(string[] args)
        {
            TcpServer server = new TcpServer();
            await server.Start();
        }
    }
}

二客户端

using System;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;

namespace Nuttykhd
{
    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 LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                        pipeline.AddLast(new StringDecoder(Encoding.UTF8));
                        pipeline.AddLast(new LengthFieldPrepender(4));
                        pipeline.AddLast(new StringEncoder(Encoding.UTF8));
                        pipeline.AddLast(new DotNettyClientHandler());
                    }));

                channel = await bootstrap.ConnectAsync("127.0.0.1", 8888);
                string clientName = "小王";
                byte[] nameBytes = Encoding.UTF8.GetBytes(clientName);
                await channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(nameBytes));

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

                // 发送消息给服务器
                SendMessage("我是客户端");

                // 停顿一段时间,模拟客户端的其他操作
                await Task.Delay(5000);

                // 发送更多消息给服务器
                SendMessage("我发 发阿飞");

                 关闭客户端连接
                //await channel.CloseAsync();
                //Console.WriteLine("Client connection closed.");
            }
            finally
            {
                await group.ShutdownGracefullyAsync();
            }
        }

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

    public class DotNettyClientHandler : SimpleChannelInboundHandler<string>
    {
        protected override void ChannelRead0(IChannelHandlerContext context, string message)
        {
            Console.WriteLine("Received message from server: " + message);
        }
    }

    public class Program
    {
        public static async Task Main()
        {
            DotNettyClient client = new DotNettyClient();
            await client.StartAsync();
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的 Spring Boot 中使用 Netty 的示例: 1. 首先,添加以下依赖到 pom.xml 文件中: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.48.Final</version> </dependency> ``` 2. 创建一个 Netty 服务器类,并实现 ChannelInboundHandlerAdapter 接口: ```java @Component @ChannelHandler.Sharable public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 处理客户端请求 ByteBuf byteBuf = (ByteBuf) msg; byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); String request = new String(bytes, "UTF-8"); System.out.println("收到客户端请求:" + request); // 响应客户端请求 String response = "Hello, " + request; ByteBuf responseBuf = Unpooled.copiedBuffer(response.getBytes()); ctx.write(responseBuf); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 3. 创建 Netty 服务器启动类,并使用 @PostConstruct 注解启动 Netty 服务器: ```java @Component public class NettyServer { private final NettyServerHandler nettyServerHandler; @Autowired public NettyServer(NettyServerHandler nettyServerHandler) { this.nettyServerHandler = nettyServerHandler; } @PostConstruct public void start() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(nettyServerHandler); } }); ChannelFuture future = serverBootstrap.bind(8080).sync(); if (future.isSuccess()) { System.out.println("Netty 服务器启动成功"); } } } ``` 以上示例中,我们创建了一个 Netty 服务器,监听 8080 端口。当客户端连接到服务器时,服务器会收到客户端请求,并响应客户端请求。 注意:如果你的 Spring Boot 应用部署在 Tomcat 或者 Jetty 容器中,则需要在启动方法上添加 @Bean 注解,以确保正确启动 Netty 服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚构的乌托邦

如果可以请打赏鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值