其他分享
首页 > 其他分享> > SpringBoot整合netty

SpringBoot整合netty

作者:互联网

引入依赖

        <!-- netty依赖 -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.42.Final</version>
            <scope>compile</scope>
        </dependency>

新建netty服务

    public void run(int port) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(eventLoopGroup)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ProverbServerHandler());

            bootstrap.bind(port).sync().channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

新建handler

public class ProverbServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 接收数据
        DatagramPacket packet = (DatagramPacket) msg;

        ByteBuf byteBuf1 = new UnpooledByteBufAllocator(false).buffer();
        // 刷新
        ctx.writeAndFlush(new DatagramPacket(byteBuf1, packet.sender()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
    }

}


来自为知笔记(Wiz)

标签:netty,DatagramPacket,SpringBoot,void,eventLoopGroup,整合,new,public
来源: https://www.cnblogs.com/chougoushi/p/14362472.html