Netty UDP 客户端发消息后接收服务器信息

在本站大神的文章的基础上,加入了我的项目需求,当客户端用UDP给服务端发送消息后,接收到服务端返回的消息再关闭客户端。

UdpServer.java
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 * UDP Server
 *
 * @author sxp
 *
 */
public class UdpServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpServerHandler());
            b.bind(8080).sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
UdpServerHandler.java
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.ThreadLocalRandom;

/**
 * UDP Server Handler Class
 *
 * @author sxp
 *
 */
public class UdpServerHandler extends SimpleChannelInboundHandler {

    private static final String[] proverbs = { "只要功夫深,铁棒磨成针。", "旧时王谢堂前燕,飞入寻常百姓家。", "洛阳亲友如相问,一片冰心在玉壶。",
            "一寸光阴一寸金,寸金难买寸光阴。", "老骥伏枥,志在千里。烈士暮年,壮心不已!" };
    private static final String[] idioms = { "马到成功", "狐假虎威", "虎头虎脑", "生龙活虎", "如雷贯耳", "持之以恒" };

    /**
     * 随机返回谚语
     */
    private String nextProverb() {
        int nextInt = ThreadLocalRandom.current().nextInt(proverbs.length);
        return proverbs[nextInt];
    }

    /**
     * 随机返回成语
     */
    private String nextIdiom() {
        int nextInt = ThreadLocalRandom.current().nextInt(idioms.length);
        return idioms[nextInt];
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String message = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println("服务端从" + msg.sender() + "接收到的消息:" + message);
        String sendMessage;
        if ("谚语".equals(message)) {
            sendMessage = nextProverb();
        } else if ("成语".equals(message)) {
            sendMessage = nextIdiom();
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(sendMessage, CharsetUtil.UTF_8), msg.sender()));
        }
        else if ("成语9".equals(message)) {
            sendMessage = "可以停了";
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(sendMessage, CharsetUtil.UTF_8), msg.sender()));
            return;
        }else {
            sendMessage = "请发送:“谚语”或者“成语”";
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(sendMessage, CharsetUtil.UTF_8), msg.sender()));
        }
    }

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

}

UdpClient.java
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * UDP Client
 *
 * @author sxp
 *
 */
public class UdpClient {

    public static Channel channel;

    public static EventLoopGroup group;

    public static void main(String[] args) throws InterruptedException {
        group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                    .remoteAddress("127.0.0.1", 8080)
                    .handler(new UdpClientHandler());
            channel = b.bind(8082).sync().channel();
            for (int i = 1; i < 10; i++) {
                String text = "成语";
                if(i == 9) {
                    text = "成语9";
                }
                channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer( text, CharsetUtil.UTF_8),
                        new InetSocketAddress("127.0.0.1", 8080)));
            }
//            channel.close();
        } finally {
//            group.shutdownGracefully();
        }
    }

    public Channel getChannel(){
        return channel;
    }

    public EventLoopGroup getGroup(){
        return group;
    }


}

UdpClientHandler.java
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 * UDP Client Handler Class
 *
 * @author sxp
 *
 */
public class UdpClientHandler extends SimpleChannelInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String receiveMessage = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println(receiveMessage);
        if(receiveMessage.equals("可以停了")) {
            UdpClient udpClient = new UdpClient();
            Channel channel = udpClient.getChannel();
            channel.close();
            EventLoopGroup group = udpClient.getGroup();
            group.shutdownGracefully();
        }
    }

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

}


 依次启动UdpServer.java和UdpClient.java中的main方法后,执行结果为:

Netty UDP 客户端发消息后接收服务器信息_第1张图片

Netty UDP 客户端发消息后接收服务器信息_第2张图片

可以发现,客户端是在执行完任务并接收到服务器返回的消息后才关闭的。 

啦啦啦啦啦啦。一起冲冲冲。

你可能感兴趣的:(netty,java)