ssjygl-xsct-service/ssjygl-xsx-common/src/main/java/com/cowr/common/plugin/NettyServerPlugin.java

94 lines
3.3 KiB
Java

package com.cowr.common.plugin;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import java.util.HashMap;
import java.util.Map;
public class NettyServerPlugin implements IPlugin {
private static Log log = Log.getLog(NettyServerPlugin.class);
private int port;
private Map<Channel, Integer> map = new HashMap<>();
private ServerBootstrap serverBootstrap;
private EventLoopGroup workerGroup;
private EventLoopGroup bossGroup;
public NettyServerPlugin(int port) {
this.port = port;
}
@Override
public boolean start() {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
try {
serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
new IdleStateHandler(5, 5, 5),
new StringEncoder(CharsetUtil.UTF_8),
new LineBasedFrameDecoder(4096),
new StringDecoder(CharsetUtil.UTF_8),
new MsgHandler()
);
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// Bind and start to accept incoming connections.
ChannelFuture f = serverBootstrap.bind(port);
// f.addListener((ChannelFutureListener) future -> {
// if (!future.isSuccess()) {
// map.remove(f.channel());
// }
// });
f.sync();
f.channel().closeFuture().sync();
return true;
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
return false;
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
@Override
public boolean stop() {
if (serverBootstrap != null) {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
serverBootstrap = null;
}
return true;
}
private static class MsgHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
}
}
}