【四、使用Netty编写UDP应用】

本章介绍如何利用Netty来编写UDP应用。内容包括创建UDP Server,使用NioDatagramChannel,定义ServerHandler处理DatagramPacket,以及构建UDP客户端并设定客户端Handler。测试时需注意,由于UDP的无连接特性,服务器和客户端不应部署在同一台机器上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目标

之前的章节我们学习了编码服务端,使用TCP通信,本章我们学习如何使用Netty构建一个UDP应用。

创建UDP Server

package com.coman404.base;

import com.coman404.base.handler.UDPServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.util.Objects;
public class UDPServer {

    public static void main(String[] args) {
        int port = 8081;
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap server = new Bootstrap();
            server.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(new UDPServerHandler());
                        }
                    });
            ChannelFuture f = server.bind(port).sync();
            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

}

注意设置的channel是NioDatagramChannel类

创建ServerHandler

public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg){
        ByteBuf byteBuf = msg.content();
        int len = byteBuf.readableBytes();
        byte[] bytes = new byte[len];
        byteBuf.readBytes(bytes);
        System.out.println(new String(bytes,StandardCharsets.UTF_8));
    }

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

UDP接收的是数据报文DatagramPacket

创建UDP客户端

public class UDPClient {
    public static void main(String[] args){

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(new UDPClientHandler());
                        }
                    });
            ChannelFuture f = bootstrap.connect("localhost",8089).sync();
            if (f.isSuccess()){
                System.out.println("连接成功");
            }
            Channel channel = f.channel();
            channel.writeAndFlush(new DatagramPacket(channel.alloc().buffer().writeBytes("hello world".getBytes(StandardCharsets.UTF_8)),new InetSocketAddress("localhost",8089)));
            channel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }

    }
}

创建客户端的Handler

public class UDPClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        ByteBuf byteBuf = msg.content();
        int len = byteBuf.readableBytes();
        byte[] bytes = new byte[len];
        byteBuf.readBytes(bytes);
        System.out.println(new String(bytes,StandardCharsets.UTF_8));
    }
}

测试UDP 的客户端和Server端时,不要在同一个机器上,因为UDP是无连接的,他们都连接在同一端口上,测试数据没有响应

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThinkLess404

有问题可以私信交流

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值