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();
    }

}




posted @ 2021-02-02 15:57  Patrick&Star  阅读(674)  评论(0编辑  收藏  举报