我使用的是springboot+maven,所以先引入pom。(参考了网上的"许多"配置,然后自己做了一下修改)
在pom.xml中引用以下代码:
io.netty netty-all 4.1.32.Final
在application.yml中引用以下代码:
netty:
tcp:
server:
host: 127.0.0.1
port: 7000
然后创建文件NettyTcpServer.java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* description:
* author:
* date: 2018-11-28 12:07
**/
@Component
public class NettyTcpServer {
private static final Logger log = LoggerFactory.getLogger(NettyTcpServer.class);
//boss事件轮询线程组
//处理Accept连接事件的线程,这里线程数设置为1即可,netty处理链接事件默认为单线程,过度设置反而浪费cpu资源
private EventLoopGroup boss = new NioEventLoopGroup(1);
//worker事件轮询线程组
//处理hadnler的工作线程,其实也就是处理IO读写 。线程数据默认为 CPU 核心数乘以2
private EventLoopGroup worker = new NioEventLoopGroup();
@Autowired
ServerChannelInitializer serverChannelInitializer;
@Value("${netty.tcp.server.port}")
private Integer port;
//与客户端建立连接后得到的通道对象
private Channel channel;
/**
* 存储client的channel
* key:ip,value:Channel
*/
public static Map map = new ConcurrentHashMap();
public static Map macMap = new HashMap();
/**
* 开启Netty tcp server服务
*
* @return
*/
public ChannelFuture start() {
//启动类
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, worker)//组配置,初始化ServerBootstrap的线程组
.channel(NioServerSocketChannel.class)///构造channel通道工厂//bossGroup的通道,只是负责连接
.childHandler(serverChannelInitializer)//设置通道处理者ChannelHandler////workerGroup的处理器
.option(ChannelOption.SO_BACKLOG, 1024)
// .option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE)//socket参数,当服务器请求处理程全满时,用于临时存放已完成三次握手请求的队列的最大长度。如果未设置或所设置的值小于1,Java将使用默认值50。
.childOption(ChannelOption.SO_KEEPALIVE, true);//启用心跳保活机制,tcp
//Future:异步任务的生命周期,可用来获取任务结果
ChannelFuture channelFuture1 = serverBootstrap.bind(port).syncUninterruptibly();//绑定端口,开启监听,同步等待
if (channelFuture1 != null && channelFuture1.isSuccess()) {
channel = channelFuture1.channel();//获取通道
log.info("Netty tcp server start success, port = {}", port);
} else {
log.error("Netty tcp server start fail");
}
return channelFuture1;
}
/**
* 停止Netty tcp server服务
*/
@PreDestroy
public void destroy() {
if (channel != null) {
channel.close();
}
try {
Future> future = worker.shutdownGracefully().await();
if (!future.isSuccess()) {
log.error("netty tcp workerGroup shutdown fail, {}", future.cause());
}
Future> future1 = boss.shutdownGracefully().await();
if (!future1.isSuccess()) {
log.error("netty tcp bossGroup shutdown fail, {}", future1.cause());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("Netty tcp server shutdown success");
}
}
然后创建ServerChannelHandler.java文件
@Component
@ChannelHandler.Sharable
public class ServerChannelHandler extends ChannelDuplexHandler {
private static Logger logger = LoggerFactory.getLogger(ServerChannelHandler.class);
@Autowired
private SelfLogsService selfLogService;
@Autowired
private SelfUserService selfUserService;
@Autowired
private SelfUserDeviceService selfUserDeviceService;
/**
* 拿到传过来的msg数据,开始处理
*
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Netty tcp server receive msg : " + msg);
ctx.channel().writeAndFlush(" response msg ").syncUninterruptibly();//发送数据,异步任务
}
/**
* 活跃的、有效的通道
* 第一次连接成功后进入的方法
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
logger.info("tcp client " + getRemoteAddress(ctx) + " connect success");
//往channel map中添加channel信息
NettyTcpServer.map.put(getIPString(ctx), ctx.channel());
}
/**
* 不活动的通道
* 连接丢失后执行的方法(client端可据此实现断线重连)
*
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//删除Channel Map中的失效Client
NettyTcpServer.map.remove(getIPString(ctx));
NettyTcpServer.macMap.remove(getIPString(ctx));
ctx.close();
}
/**
* 心跳机制,超时处理
*
* @param ctx
* @param evt
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
String socketString = ctx.channel().remoteAddress().toString();
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) {
logger.info("Client: " + socketString + " READER_IDLE 读超时");
ctx.disconnect();//断开
} else if (event.state() == IdleState.WRITER_IDLE) {
logger.info("Client: " + socketString + " WRITER_IDLE 写超时");
ctx.disconnect();
} else if (event.state() == IdleState.ALL_IDLE) {
logger.info("Client: " + socketString + " ALL_IDLE 总超时");
ctx.disconnect();
}
}
}
/**
* 获取client对象:ip+port
*
* @param ctx
* @return
*/
public String getRemoteAddress(ChannelHandlerContext ctx) {
String socketString = "";
socketString = ctx.channel().remoteAddress().toString();
return socketString;
}
/**
* 获取client的ip
*
* @param ctx
* @return
*/
public String getIPString(ChannelHandlerContext ctx) {
String ipString = "";
String socketString = ctx.channel().remoteAddress().toString();
int colonAt = socketString.indexOf(":");
ipString = socketString.substring(1, colonAt);
return ipString;
}
创建ServerChannelInitializer.java文件
/**
* description: 通道初始化,主要用于设置各种Handler
* author:
* date: 2018-11-28 14:55
**/
@Component
public class ServerChannelInitializer extends ChannelInitializer {
@Autowired
ServerChannelHandler serverChannelHandler;
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法
pipeline.addLast("idleStateHandler",
new IdleStateHandler(5, 0, 0, TimeUnit.MINUTES));
//字符串编解码器
pipeline.addLast(
new StringDecoder(),
new StringEncoder()
);
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 4, -8, 0));
// pipeline.addLast("byteArrayEncoder", new ByteArrayEncoder());
//自定义Handler
pipeline.addLast("serverChannelHandler", serverChannelHandler);
}
}
至此,大工告成,因为我自己修改的配置地方不多。