码迷,mamicode.com
首页 > Web开发 > 详细

Netty实现简单UDP服务器

时间:2018-01-11 16:13:55      阅读:393      评论:0      收藏:0      [点我收藏+]

标签:close   cep   gpo   try   java.net   package   adl   received   tac   

本文参考《Netty权威指南》

文件列表:

├── ChineseProverbClientHandler.java
├── ChineseProverbClient.java
├── ChineseProverbServerHandler.java
└── ChineseProverbServer.java

 

package com.xh.netty.test12;

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;

/**
 * Created by root on 1/11/18.
 */
public class ChineseProverbServer {
    public void run(int port) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChineseProverbServerHandler());

            bootstrap.bind(port).sync().channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        ChineseProverbServer server = new ChineseProverbServer();
        server.run(8080);
    }
}

 

package com.xh.netty.test12;

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;

/**
 * Created by root on 1/11/18.
 */
public class ChineseProverbServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static String[] DIRC = {"哈哈哈哈", "呵呵呵", "嘻嘻嘻"};

    public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String req = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println(req);
        if (req.equalsIgnoreCase("QUERY")) {
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("RESULT:" + nextQuote(), CharsetUtil.UTF_8), packet.sender()));


        }else {
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("RESULT:" + "ERR", CharsetUtil.UTF_8), packet.sender()));
        }
    }

    private String nextQuote() {
        int quote = ThreadLocalRandom.current().nextInt(DIRC.length);
        return DIRC[quote];
    }
}

 

package com.xh.netty.test12;

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;

/**
 * Created by root on 1/11/18.
 */
public class ChineseProverbClient {
    public void run(int port) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChineseProverbClientHandler());
            Channel channel = bootstrap.bind(7070).sync().channel();
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QUERY", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", port))).sync();
            if (!channel.closeFuture().await(15000)) {
                System.out.println("out of time");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }  
    }

    public static void main(String[] args) {
        new ChineseProverbClient().run(8080);
    }

}

 

package com.xh.netty.test12;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 * Created by root on 1/11/18.
 */
public class ChineseProverbClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String result = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println("client>>>" + result);
        ctx.close();
    }
}

 

Netty实现简单UDP服务器

标签:close   cep   gpo   try   java.net   package   adl   received   tac   

原文地址:https://www.cnblogs.com/lanqie/p/8267498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!