提问端
public class UdpQuestionSide {
public final static String QUESTION = "告诉我一句古诗" ;
public void run ( int port) throws Exception{
EventLoopGroup group = new NioEventLoopGroup ( ) ;
try {
Bootstrap b = new Bootstrap ( ) ;
b. group ( group)
. channel ( NioDatagramChannel. class )
. handler ( new QuestoinHandler ( ) ) ;
Channel ch = b. bind ( 0 ) . sync ( ) . channel ( ) ;
ch. writeAndFlush ( new DatagramPacket (
Unpooled. copiedBuffer ( QUESTION, CharsetUtil. UTF_8) ,
new InetSocketAddress ( "127.0.0.1" , port)
) ) ;
if ( ! ch. closeFuture ( ) . await ( 15000 ) ) {
System. out. println ( "查询超时!" ) ;
}
} catch ( Exception e) {
group. shutdownGracefully ( ) ;
}
}
public static void main ( String [ ] args) throws Exception{
int answerPort = 8080 ;
new UdpQuestionSide ( ) . run ( answerPort) ;
}
}
提问端handler
public class QuestoinHandler extends
SimpleChannelInboundHandler < DatagramPacket> {
@Override
protected void channelRead0 ( ChannelHandlerContext ctx, DatagramPacket msg)
throws Exception {
String response = msg. content ( ) . toString ( CharsetUtil. UTF_8) ;
if ( response. startsWith ( UdpAnswerSide. ANSWER) ) {
System. out. println ( response) ;
ctx. close ( ) ;
}
}
@Override
public void exceptionCaught ( ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause. printStackTrace ( ) ;
ctx. close ( ) ;
}
}
应答端
public class UdpAnswerSide {
public final static String ANSWER = "古诗来了:" ;
public void run ( int port) throws Exception{
EventLoopGroup group = new NioEventLoopGroup ( ) ;
try {
Bootstrap b = new Bootstrap ( ) ;
b. group ( group)
. channel ( NioDatagramChannel. class )
. handler ( new AnswerHandler ( ) ) ;
ChannelFuture f = b. bind ( port) . sync ( ) ;
System. out. println ( "应答服务已启动....." ) ;
f. channel ( ) . closeFuture ( ) . sync ( ) ;
} finally {
group. shutdownGracefully ( ) ;
}
}
public static void main ( String [ ] args) throws Exception{
int port = 8080 ;
new UdpAnswerSide ( ) . run ( port) ;
}
}
应答端handler
public class AnswerHandler extends
SimpleChannelInboundHandler < DatagramPacket> {
private static final String[ ] DICTIONARY = {
"只要功夫深,铁棒磨成针。" ,
"旧时王谢堂前燕,飞入寻常百姓家。" ,
"洛阳亲友如相问,一片冰心在玉壶。" ,
"一寸光阴一寸金,寸金难买寸光阴。" ,
"老骥伏枥,志在千里,烈士暮年,壮心不已" } ;
private static Random r = new Random ( ) ;
private String nextQuote ( ) {
return DICTIONARY[ r. nextInt ( DICTIONARY. length- 1 ) ] ;
}
@Override
protected void channelRead0 ( ChannelHandlerContext ctx,
DatagramPacket packet)
throws Exception {
String req = packet. content ( ) . toString ( CharsetUtil. UTF_8) ;
System. out. println ( req) ;
if ( UdpQuestionSide. QUESTION. equals ( req) ) {
ctx. writeAndFlush (
new DatagramPacket (
Unpooled. copiedBuffer (
UdpAnswerSide. ANSWER+ nextQuote ( ) ,
CharsetUtil. UTF_8) ,
packet. sender ( ) ) ) ;
}
}
@Override
public void exceptionCaught ( ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx. close ( ) ;
cause. printStackTrace ( ) ;
}
}