Java - UDPServer (Netty 改写Server & Client)
controller:
@EnableAsync
@SpringBootApplication
@EnableScheduling
public class UdpServerApplication implements CommandLineRunner {
@Autowired
private ChineseProverbServer servers;
public static void main(String[] args) {
SpringApplication.run(UdpServerApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
//加载监听线程
new Thread() {
@Override
public void run() {
super.run();
servers.run(port);
}
}.start();
}
}
server:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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;
@Service
public class ChineseProverbServer {
private static final Logger LOGGER = LoggerFactory.getLogger(ChineseProverbServer.class);
@Autowired
private ChineseProverbServerHandler chineseProverbServerHandler;
public void run(int port) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
.handler(chineseProverbServerHandler);
//option(ChannelOption.SO_BACKLOG, 2048) serverSocketchannel的设置,链接缓冲池的大小
bootstrap.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException e) {
LOGGER.error("The service may be an exception"+ e.getMessage());
} finally {
eventLoopGroup.shutdownGracefully();
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nokia.udp_server.send.UdpSend;
import com.nokia.udp_server.util.UnicodeUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
@Component
public class ChineseProverbServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
private static final Logger LOGGER = LoggerFactory.getLogger(ChineseProverbServerHandler.class);
private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private static final Map<String, DatagramPacket> getPacket = new ConcurrentHashMap<>();
private static final Map<String, ChannelHandlerContext> getctx = new ConcurrentHashMap<>();
/**
* newCachedThreadPool:用来创建一个可以无限扩大的线程池,适用于服务器负载较轻,执行很多短期异步任务。
* newFixedThreadPool:创建一个固定大小的线程池,因为采用无界的阻塞队列,所以实际线程数量永远不会变化,适用于可以预测线程数量的业务中,或者服务器负载较重,对当前线程数量进行限制。
* newSingleThreadExecutor:创建一个单线程的线程池,适用于需要保证顺序执行各个任务,并且在任意时间点,不会有多个线程是活动的场景。
* newScheduledThreadPool:可以延时启动,定时启动的线程池,适用于需要多个后台线程执行周期任务的场景。
* newWorkStealingPool:创建一个拥有多个任务队列的线程池,可以减少连接数,创建当前可用cpu数量的线程来并行执行,适用于大耗时的操作,可以并行来执行
*
*/
//private static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
private static final ExecutorService CachedThreadPool = Executors.newCachedThreadPool();
/**
* 在这个方法中,形参packet客户端发过来的DatagramPacket对象
* DatagramPacket 类解释
* 1.官网是这么说的:
* The message container that is used for {@link DatagramChannel} to communicate with the remote peer.
* 翻译:DatagramPacket 是消息容器,这个消息容器被 DatagramChannel使用,作用是用来和远程设备交流
* 2.看它的源码我们发现DatagramPacket是final类不能被继承,只能被使用。我们还发现DatagramChannel最终实现了AddressedEnvelope接口,接下来我们看一下AddressedEnvelope接口。
* AddressedEnvelope接口官网解释如下:
* A message that wraps another message with a sender address and a recipient address.
* 翻译:这是一个消息,这个消息包含发送者和接受者消息
* 3.那我们知道了DatagramPacket它包含了发送者和接受者的消息,
* 通过content()来获取消息内容
* 通过sender();来获取发送者的消息
* 通过recipient();来获取接收者的消息。
*
* 4.public DatagramPacket(ByteBuf data, InetSocketAddress recipient) {}
* 这个DatagramPacket其中的一个构造方法,data 是发送内容;是发送都信息。
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
getctx.put("ctx", ctx);
getPacket.put("packet", packet);
ByteBuf buf = packet.copy().content();
LOGGER.info("receive ip: {} port: {}", packet.sender().getAddress().getHostAddress(), packet.sender().getPort());
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String data = new String(req, "UTF-8");
String payload_hex = Hex.encodeHexString(req);
CachedThreadPool.execute(new Runnable(){
public void run(){
//数据逻辑处理部分 需自行实现
decodeData(data,payload_hex,ctx, packet);
}
});
}
public DatagramPacket getPacket() {
return getPacket.get("packet");
}
public ChannelHandlerContext getctx() {
return getctx.get("ctx");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
cause.printStackTrace();
}
}
client:
@Autowired
private ChineseProverbServerHandler cpsh;
byte[] bytes = Hex.decodeHex("response message".toCharArray());//data.getBytes("UTF-8");
InetSocketAddress ita = new InetSocketAddress(address,port);
DatagramPacket datas = new DatagramPacket(Unpooled.copiedBuffer(bytes), ita);
cpsh.getctx().writeAndFlush(datas); //向客户端发送消息