Netty-UDP通讯(服务端)

Maven 引入

<!-- netty依赖 springboot2.x自动导入版本 -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>

        <!-- 这里我用到了@slf4j 所以引入这个jar -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

 初始化服务

/**
 * @author 
 */
@Slf4j
public class BootNettyUdpServer {

    /**
     * 启动服务
     */
    public void bind(int port) {
        System.out.println("-------------------------------udpServer-------------------------!");
        log.error("-------------------------------udpServer-------------------------");
        //表示服务器连接监听线程组,专门接受 accept 新的客户端client 连接
        EventLoopGroup bossLoopGroup  = new NioEventLoopGroup();
        try {
            //1,创建netty bootstrap 启动类
            Bootstrap serverBootstrap = new Bootstrap();
            //2、设置boostrap 的eventLoopGroup线程组
            serverBootstrap = serverBootstrap.group(bossLoopGroup);
            //3、设置NIO UDP连接通道
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            //4、设置通道参数 SO_BROADCAST广播形式
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true);
            //5、设置处理类 装配流水线
            serverBootstrap = serverBootstrap.handler(new BootNettyUdpSimpleChannelInboundHandler());
            //6、绑定server,通过调用sync()方法异步阻塞,直到绑定成功
            ChannelFuture f = serverBootstrap.bind(port).sync();

            log.error(BootNettyUdpServer.class.getName()+" started and listend on "+f.channel().localAddress());

            //7、监听通道关闭事件,应用程序会一直等待,直到channel关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            System.out.println("netty udp close!");
            //8 关闭EventLoopGroup,
            bossLoopGroup.shutdownGracefully();
        }
    }
}

接收数据

 

/**
 * @author 
 */
@Slf4j
public class BootNettyUdpSimpleChannelInboundHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        try {
            // 读取数据
            ByteBuf byteBuf = packet.content();
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            System.out.println("receive client msg:" + new String(bytes));
            String test = "0020A5A500000000";
            byte[] resBytes = test.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(Unpooled.copiedBuffer(resBytes), packet.sender());
            ctx.writeAndFlush(sendPacket);


        } catch (Exception e) {

        }
    }

}

启动服务

@SpringBootApplication
@EnableAsync
public class UdpApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(UdpApplication.class);
//启动服务
        new BootNettyUdpServer().bind(51880);
 
    }
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值