Netty(六)UDP在netty中的使用

来源:互联网 发布:海盗船mac驱动 编辑:程序博客网 时间:2024/06/07 21:07

关于UDP的介绍,这里不在阐述。
相比于TCP而言,UDP不存在客户端和服务端的实际链接,因此不需要为连接(ChannelPipeline)设置handler。

 服务端:

SearchServer.java

package nettytest.udptest.udptest1;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.Unpooled;import io.netty.channel.*;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 org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Created by Lovell on 9/29/16. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class Server {    private static Logger logger = LoggerFactory.getLogger(Server.class);    /**     * udp服务端,接受客户端发送的广播     */    public static void initServer() {        EventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap bootstrap = new Bootstrap();            bootstrap.group(group)                    .channel(NioDatagramChannel.class)                    .option(ChannelOption.SO_BROADCAST, true)                    .handler(new UdpServerHandler());            Channel channel = bootstrap.bind(AppConstants.SEARCH_PORT).sync().channel();            channel.closeFuture().await();        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            group.shutdownGracefully();        }    }    private static class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {        @Override        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {            // 因为Netty对UDP进行了封装,所以接收到的是DatagramPacket对象。            String req = msg.content().toString(CharsetUtil.UTF_8);            System.out.println(req);            if ("hello!!!".equals(req)) {                ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(                        "结果:", CharsetUtil.UTF_8), msg.sender()));            }        }    }}

客户端:

Client.java

package nettytest.udptest.udptest1;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.Unpooled;import io.netty.channel.*;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 org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.net.InetSocketAddress;/** * Created by Lovell on 9/29/16. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class Client {    private static Logger logger = LoggerFactory.getLogger(Client.class);    public static final int MessageReceived = 0x99;    private int scanPort;    public Client(int scanPort) {        this.scanPort = scanPort;    }    private static class ClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {        @Override        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {            String response = msg.content().toString(CharsetUtil.UTF_8);            if(response.startsWith("结果:")){                System.out.println(response);                ctx.close();            }        }    }    public void sendPackage() {        EventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap b = new Bootstrap();            b.group(group)                    .channel(NioDatagramChannel.class)                    .option(ChannelOption.SO_BROADCAST, true)                    .handler(new ClientHandler());            Channel ch = b.bind(0).sync().channel();            ch.writeAndFlush(new DatagramPacket(                    Unpooled.copiedBuffer("hello!!!", CharsetUtil.UTF_8),                    new InetSocketAddress("255.255.255.255", scanPort))).sync();            logger.info("Search, sendPackage()");            // QuoteOfTheMomentClientHandler will close the DatagramChannel when a            // response is received.  If the channel is not closed within 5 seconds,            // print an error message and quit.            // 等待15秒钟            if (!ch.closeFuture().await(15000)) {                logger.info("Search request timed out.");            }        }catch (Exception e){            e.printStackTrace();            logger.info("Search, An Error Occur ==>" + e);        }finally {            group.shutdownGracefully();        }    }}

测试:

package nettytest.udptest.udptest1;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Created by Lovell on 9/29/16. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class Test {    private static Logger logger = LoggerFactory.getLogger(Test.class);    @org.junit.Test    public void test1() throws Exception {        Server.initServer();    }    @org.junit.Test    public void test2() throws Exception {        Client client = new Client(AppConstants.SEARCH_PORT);        client.sendPackage();    }}
来自:http://www.cnblogs.com/orange1438/p/5148850.html

0 0
原创粉丝点击