Netty的UDP通信心得

更新时间:2024-04-19 20:45:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Netty的UDP通信心得

1.服务端代码

public final class QuoteOfTheMomentServer { private static final int PORT = Integer.parseInt(System.getProperty(\, \)); public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new QuoteOfTheMomentServerHandler()); b.bind(PORT).sync().channel().closeFuture().await(); } finally { group.shutdownGracefully(); } } } 2.客户端代码

public final class QuoteOfTheMomentClient { static final int PORT = Integer.parseInt(System.getProperty(\, \)); public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new QuoteOfTheMomentClientHandler()); Channel ch = b.bind(0).sync().channel(); // Broadcast the QOTM request to port 8080. ch.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer(\, CharsetUtil.UTF_8), new InetSocketAddress(\, PORT))).sync(); // 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. if (!ch.closeFuture().await(5000)) { System.err.println(\); } } finally { group.shutdownGracefully(); } } } 注意channel(NioDatagramChannel.class)此句代表是UDP 3.可以不需要写编码和解码代码,直接写

(1)channel public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } Handler即可,注意客户端抛异常时需要关闭

(2)注意包长度限制if (packet.content().readableBytes()< 最小包长度) { } return;// (3) 4.解包,

public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception

packet.content()即ByteBuf然后按照协议读取即可;

5.发包,解析完成后,按照协议组成ByteBuf发送数据包,如果一个ByteBuf不方便写代码就写多个ByteBuf,发送时按顺序放在参数里就行了

DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(ByteBuf... buffers), packet.sender()); ctx.writeAndFlush(data);

6.调试和查看包

(1)Arrays.toString(ByteBuf.array())查看byte[]数组内容

(2)保留数据,注意最好使用byte[]或者转16进制字符串保存,最好不用字符串保留数据(字符串类型数据除外)

(3)数据不要进行过多的转换和操作,以免发生数据错误,造成调试问题

代码详见:http://www.tuicool.com/articles/bQF3qy

https://github.com/netty/netty/tree/4.0/example/src/main/java/io/netty/example/qotm

本文来源:https://www.bwwdw.com/article/br2p.html

Top