项目需求:搭建服务与设备进行socket通信;与api服务端进行http请求(或websocket)通信传递消息;
项目环境:IDEA+Maven ;springboot;mybatis;netty;
1.服务端DiscardServer
/**
* 丢弃任何进入的数据 启动服务端的DiscardServerHandler
*/
@Component
public class DiscardServer{
public static class SingletionDiscardServer
{
static final DiscardServer instance=new DiscardServer();
}
public static DiscardServer getInstance(){
return SingletionDiscardServer.instance;
}
private EventLoopGroup bossGroup ;
private EventLoopGroup workerGroup;
private ServerBootstrap server;
private ChannelFuture future;
protected Logger logger = LoggerFactory.getLogger(getClass());
public void start(){
bossGroup = new NioEventLoopGroup();// 用于处理客户端的连接请求
workerGroup = new NioEventLoopGroup();//用于处理与各个客户端连接的 IO 操作
try {
server = new ServerBootstrap();
//绑定处理group
server = server.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
//定义可连接的客户端队列大小
.option(ChannelOption.SO_BACKLOG, 128)
//有数据立即发送;积攒一定数据量再发送用TCP_CORK
.option(ChannelOption.TCP_NODELAY, true)
//保持连接,2小时内无数据通信TCP发送探测报文
.childOption(ChannelOption.SO_KEEPALIVE, true)
//允许重复使用本地地址和端口
.childOption(ChannelOption.SO_REUSEADDR, true)
//一个连接的远端关闭时本地端是否关闭,默认值为False。值为False时,
// 连接自动关闭;为True时,触发ChannelInboundHandler的userEventTriggered()方法,
// 事件为ChannelInputShutdownEvent
.childOption(ChannelOption.ALLOW_HALF_CLOSURE, true)
//处理新连接
.childHandler(new ChildChannelHandler());
//异步地绑定服务器;
// 调用sync()方法阻塞等待直到绑定完成
future = server.bind(8090).sync();
logger.info("服务器启动开始监听端口: 8090");
//获取 Channel 的 CloseFuture,并且阻塞当前线程直到它完成
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//优雅退出,释放线程资源
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
2.ChildChannelHandler
public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
static final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
protected void initChannel(SocketChannel socketChannel) throws Exception {
/* LineBasedFrameDecoder的工作原理是&#