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

}




我会写代码+代码改变世界=我会改变世界! 为什么要改变世界? 如果无法改变世界,那么,世界就会改变我......
原文地址:https://www.cnblogs.com/chougoushi/p/14362472.html