1.引入相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu.tju</groupId>
<artifactId>nettyudp</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.73.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
</project>
2.创建服务器端处理器类:
package cn.edu.tju;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import java.util.concurrent.ThreadLocalRandom;
public class ServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
private String[] reward={"一等奖","二等奖","三等奖","四等奖","五等奖"};
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
String req=msg.content().toString(CharsetUtil.UTF_8);
System.out.println(req);
int index=ThreadLocalRandom.current().nextInt(reward.length);
ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("message from server: "+reward[index], CharsetUtil.UTF_8),msg.sender()));
}
}
3.创建服务器端主类:
package cn.edu.tju;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
public class UdpServer {
private static int port=8866;
public static void main(String[] args) {
EventLoopGroup group=new NioEventLoopGroup();
try{
Bootstrap bootstrap=new Bootstrap();
bootstrap.group(group).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST,false)
.handler(new ServerHandler());
bootstrap.bind(port).sync().channel().closeFuture().await();
}catch (Exception ex){
System.out.println(ex.getMessage());
}finally {
group.shutdownGracefully();
}
}
}
4.创建客户端处理器类:
package cn.edu.tju;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
public class ClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
String str=msg.content().toString(CharsetUtil.UTF_8);
System.out.println(str);
}
}
5.创建客户端主类:
package cn.edu.tju;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
public class UdpClient {
private static int port=8866;
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 ClientHandler());
Channel ch=b.bind(0).sync().channel();
ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("message from client: hello,world",CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255",port)));
if(!ch.closeFuture().await(60000)){
System.out.println("超时");
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}finally {
group.shutdownGracefully();
}
}
}
6.分别运行服务器端主类和客户端主类:
结果如下: