springboot集成netty使用udp协议实现消息接收与转发

一、转发服务

1、创建NettyServer,使用线程池实现异步处理

**
 * udp服务
 */
public class NettyServer {

    private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class);

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 10, 60,
            TimeUnit.SECONDS, new SynchronousQueue<Runnable>()
            , r -> new Thread(r,"NettyServer-Thread-" + threadNumber.getAndIncrement()));

    @Autowired
    NettyServerHandler nettyServerHandler;

    public void start(InetSocketAddress address) {
        try {
            executor.execute(() -> {
                EventLoopGroup group = new NioEventLoopGroup();
                try {
                    Bootstrap b = new Bootstrap();
                    b.group(group)
                            .channel(NioDatagramChannel.class)
                            // udp协议
                            .option(ChannelOption.SO_BROADCAST, true)
                            .handler(nettyServerHandler);
                    LOG.info("--------------服务端upd服务启动----------------");
                    ChannelFuture channelFuture = b.bind(address.getAddress(),address.getPort()).sync();
                    System.out.println("服务器正在监听消息......");
                    channelFuture.channel().closeFuture().await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    group.shutdownGracefully();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2、创建消息处理类NettyServerHandler

/**
 * 消息接收与转发
 */
@Component
public class NettyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final Logger LOG = LoggerFactory.getLogger(NettyServerHandler.class);

    @Value("${nettyClient.ip}")
    private String clientIp;

    @Value("${nettyClient.port}")
    private int clientPort;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
        ByteBuf byteBuf = msg.content();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        byteBuf = Unpooled.copiedBuffer(new String(bytes).getBytes(StandardCharsets.UTF_8));
        LOG.info("接收到消息:" + new String(bytes));
        // 将消息转发给客户端
        ctx.writeAndFlush(new DatagramPacket(byteBuf, new InetSocketAddress(clientIp, clientPort)));
    }

}

3、创建NettyBean用于保存连接上下文

public class NettyBean {
    /**
     * 保存连接上下文
     */
    private Map<String, ChannelHandlerContext> channel = new HashMap<>(16);

    public Map<String, ChannelHandlerContext> getChannel() {
        return channel;
    }

    public void setChannel(String key, ChannelHandlerContext val) {
        this.channel.put(key, val);
    }
}

4、配置类NettyConfig

@Configuration
public class NettyConfig {

    @Value("${nettyServer.ip}")
    private String serverIp;

    @Value("${nettyServer.port}")
    private int serverPort;

    @Bean
    public NettyBean getNettyBean() {
        return new NettyBean();
    }

    @Bean
    public NettyServer getNettyClient() {
        NettyServer nettyServer = new NettyServer();
        nettyServer.start(new InetSocketAddress(serverIp, serverPort));
        return nettyServer;
    }
}

5、配置文件

server:
  port: 10019
  
nettyServer:
  ip: 127.0.0.1
  port: 8888

nettyClient:
  ip: 127.0.0.1
  port: 8889

二、客户端接收

客户端与转发服务同理,与转发服务的区别为无需再次转发消息,而是直接处理。

NettyClient

public class NettyClient {
    private static final Logger LOG = LoggerFactory.getLogger(NettyClient.class);

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 10, 60,
            TimeUnit.SECONDS, new SynchronousQueue<Runnable>()
            , r -> new Thread(r,"NettyClient-Thread" + threadNumber.getAndIncrement()));

    @Autowired
    NettyClientHandler nettyClientHandler;

    public void start(InetSocketAddress address) {
        try {
            executor.execute(() -> {
                EventLoopGroup group = new NioEventLoopGroup();
                try {
                    Bootstrap b = new Bootstrap();
                    b.group(group)
                            .channel(NioDatagramChannel.class)
                            .option(ChannelOption.SO_BROADCAST, true)
                            .handler(nettyClientHandler);
                    LOG.info("--------------客户端upd服务启动----------------");
                    Channel channel = b.bind(address.getAddress(),address.getPort()).sync().channel();
                    channel.closeFuture().await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    group.shutdownGracefully();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

NettyClientHandler

@Component
public class NettyClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Autowired
    private NettyBean nettyBean;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        System.out.println("客户端收到消息:" + msg.content().toString(StandardCharsets.UTF_8));
        //保存连接上下文
        nettyBean.setChannel(msg.sender().getHostName(), ctx);
    }
}

三、测试

使用测试工具发送消息进行测试
测试发送消息
转发服务收到消息并转发到客户端
转发服务收到消息
客户端收到消息
客户端收到消息

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个简单的示例代码,演示了如何在Spring Boot应用程序中集成Netty实现UDP通信: 首先,我们需要添加NettySpring Boot的依赖项。在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 接下来,我们创建一个UDP服务类,实现Netty的ChannelInboundHandlerAdapter接口,以处理接收到的UDP消息。我们将其命名为UdpServerHandler类。 ```java @Component public class UdpServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { DatagramPacket packet = (DatagramPacket) msg; ByteBuf buf = (ByteBuf) packet.copy().content(); byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String message = new String(req, CharsetUtil.UTF_8); System.out.println("Received message: " + message); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` 然后,我们创建一个UDP服务器类,使用UdpServerHandler类处理接收到的UDP消息。 ```java @Component public class UdpServer { @Autowired private UdpServerHandler udpServerHandler; private EventLoopGroup group = new NioEventLoopGroup(); @PostConstruct public void start() { try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(udpServerHandler); b.bind(9999).sync().channel().closeFuture().await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } } ``` 最后,我们需要在Spring Boot应用程序中启用UDP服务器,通过添加@EnableAutoConfiguration和@ComponentScan注解来实现。 ```java @SpringBootApplication @EnableAutoConfiguration @ComponentScan("com.example") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,我们就可以通过UDP协议Spring Boot应用程序中实现数据通信了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值