在springboot工程中集成netty框架实现UDP的接收与发送,话不多说,直接上代码。
1、Java中基于netty实现
- 客户端向服务端发送“成语”或“谚语”时,服务端会随机生成对应的成语和谚语返回给客户端;
- 服务端如果接收到除“谚语”和“成语”的其他字符串则发送“请发送‘谚语’或‘成语’”的提示语;
1.1、服务端
public class UdpServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap
.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(new UdpServerHandler());
bootstrap
.bind(8082)
.sync()
.channel()
.closeFuture()
.sync();
} finally {
group.shutdownGracefully();
}
}
}
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
private static final String[] proverbs = { "只要功夫深,铁棒磨成针。", "旧时王谢堂前燕,飞入寻常百姓家。", "洛阳亲友如相问,一片冰心在玉壶。", "一寸光阴一寸金,寸金难买寸光阴。", "老骥伏枥,志在千里。烈士暮年,壮心不已!" };
private static final String[] idioms = { "马到成功", "狐假虎威", "虎头虎脑", "生龙活虎", "如雷贯耳", "持之以恒" };
/**
* 随机返回谚语
*/
private String nextProverb() {
int nextInt = ThreadLocalRandom.current().nextInt(proverbs.length);
return proverbs[nextInt];
}
/**
* 随机返回成语
*/
private String nextIdiom() {
int nextInt = ThreadLocalRandom.current().nextInt(idioms.length);
return idioms[nextInt];
}
@Override
protected void channelR