netty创建udp客户端

来源:互联网 发布:顾比均线的通达信源码 编辑:程序博客网 时间:2024/05/16 19:07

介绍本书给大家,netty最新的技术书籍,已有实体书籍,我买了一本,但内容没有这个全面

https://waylau.gitbooks.io/essential-netty-in-action/

具体请参照我上一篇文章,netty的udp服务端

启动类

package com.use.socket.udp.client;



import java.net.InetSocketAddress;


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;


public class UdpClient {
public void run(int port,String context)throws Exception{

EventLoopGroup group=new NioEventLoopGroup();
try {
Bootstrap b=new Bootstrap();
b.group(group).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new UdpClientHandler());
Channel ch=b.bind(0).sync().channel();


ch.writeAndFlush(
new DatagramPacket(
Unpooled.copiedBuffer(context, CharsetUtil.UTF_8), 
new InetSocketAddress("locahost", port)));

if(!ch.closeFuture().await(15000)){
System.out.println("查询超时");
}

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
group.shutdownGracefully();
}
}

public static void main(String[] args) throws Exception {
int port=8080;
String context="qwww";
if(args.length>0){
try {
port=Integer.parseInt(args[0]);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
new UdpClient().run(port,context);
}

}

具体实现方法

package com.use.socket.udp.client;


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




public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket>{


@Override
protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
// TODO Auto-generated method stub
String response=packet.content().toString(CharsetUtil.UTF_8);
if(response.startsWith("结果:")){
System.out.println(response);
ctx.close();
}
}


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


}