1.pom的依赖
io.netty netty-all5.0.0.Alpha2
2.ByteBuf的使用
2.1使用UDP发送消息
public void SendMessage( ByteBuf byteBuf){
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(NioDatagramChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
}
});
Channel channel = bootstrap.bind(9092).sync().channel();
System.out.println("1111111");
System.out.println(textconfig.getHost()+"======================="+textconfig.getPort2());
InetSocketAddress address = new InetSocketAddress(textconfig.getHost(),textconfig.getPort2());
channel.writeAndFlush(new io.netty.channel.socket.DatagramPacket(byteBuf, address)).sync();
// channel.closeFuture().await();
} catch (Exception e) {
// e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
2.2接收UDP的消息
DatagramSocket ds=new DatagramSocket(Integer.parseInt(value)); byte[] buf = new byte[5000];//接受UDP端口数据 //创建接收数据的UDP包 new DatagramPacket(byte[],length); java.net.DatagramPacket dp = new java.net.DatagramPacket(buf, 5000); //接受数据 ds.receive(dp); ByteBuf byteBuf = Unpooled.buffer(0); byteBuf.writeBytes(buf, 0, dp.getLength());
2.3 ByteBuf的使用的方法
2.3.1:根据字节的下标获取到对应的的字节的数据
example:
int index = 8; //字节下标
int iType = byteBuf.getIntLE(index);
2.3.2:根据字节的下表获取对应长度的数据
example:
i = byteBuf.getIntLE(byteBuf.readableBytes() - 4);
2.3.3:创建ByteBuf的数组:
example:
ByteBuf byteBuf = Unpooled.buffer(0);



