Netty创建upd服务端

这里需要netty的jar包文件,我已经上传到百度云,提供下载:

这里使用的是netty5

http://pan.baidu.com/s/1hr2VBzY

服务端:

package com.use.socket.udp.Server;



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;


public class UdpServer {
// 相比于TCP而言,UDP不存在客户端和服务端的实际链接,因此
    // 不需要为连接(ChannelPipeline)设置handler
    public void run(int port)throws Exception{
        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(port).sync().channel().closeFuture().await();
            System.out.println("启动成功");
        }
        finally {
            group.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws Exception{
        int port = 8080;
        if(args.length>0){
            try{
                port = Integer.parseInt(args[0]);
            }
            catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        new UdpServer().run(port);
    }

}




package com.use.socket.udp.Server;


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;


public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket>{
private static final  String[] DICTIONARY={
            "hello world",
            "C++",
            "C#",
            "Java",
            "python"
    };


    private String nextQuoto(){
        // 线程安全的随机类:ThreadLocalRandom
        int quoteId = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
        return DICTIONARY[quoteId];
    }


    @Override
    public void messageReceived(ChannelHandlerContext channelHandlerContext,
                                   DatagramPacket datagramPacket) throws Exception {
        // 因为Netty对UDP进行了封装,所以接收到的是DatagramPacket对象。
        String req = datagramPacket.content().toString(CharsetUtil.UTF_8);
        System.out.println("udp service收到"+req);


       /* if("aaa".equals(req)){
            channelHandlerContext.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                    "resourlt:"+nextQuoto(),CharsetUtil.UTF_8),datagramPacket.sender()));
        }else{
        channelHandlerContext.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                     "resourlt:"+nextQuoto(),CharsetUtil.UTF_8),datagramPacket.sender()));
        }*/
    }


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


可以使用工具测试:


查看eclipse中udp服务端数据:


可以接收到,自此,netty的udp服务端执行完毕

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值