User Datagram Protocal直接用IP协议进行数据发送,提供的是面向无连接,不可靠的数据投递服务。使用UDP的应用程序必须自己解决数据丢失,重复,排序,差错确认等问题。UDP数据包的格式如下:
UDP协议的特点:
1、无连接,在数据传输前,发送方和接收方互换信息使双方同步
2、UDP对接收到的数据不发确认信号
3、UDP传输数据比TCP快,系统开销也小,常用于可靠性要求不高的数据传输,如视频语音图片以及简单文件传输
public class ChineseProverbServer {
public static void main(String[] args) {
int port = 8089;
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChineseProverbServerHandler());
b.bind(port).sync().channel().closeFuture().await();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
static class ChineseProverbServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
private static final String[] DICTIONARY = {"只要功夫深铁杵磨成针", "旧时王谢堂前燕飞入寻常百姓家", "洛阳亲友如相问一片冰心在玉壶", "一寸光阴一寸金寸金难买寸光阴", "老骥伏枥志在千里"};
private String nextQuote() {
int quoteId = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
return DICTIONARY[quoteId];
}
@Override
protected void channelRead0(ChannelHandlerContext ctx,
DatagramPacket msg) throws Exception {
String request = msg.content().toString(CharsetUtil.UTF_8);
System.out.println(request);
if ("谚语字典查询".equals(request)) {
ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询结果:" + nextQuote(), CharsetUtil.UTF_8), msg.sender()));
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
cause.printStackTrace();
}
}
}
public class ChineseProverbClient {
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new ChineseProverbClientHandlert());
Channel ch = b.bind(0).sync().channel();
ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询", CharsetUtil.UTF_8), new InetSocketAddress("localhost", 8089)));
if (!ch.closeFuture().await(15000)) {
System.out.println("查询超时!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
static class ChineseProverbClientHandlert 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();
}
}
}
}