72 lines
2.2 KiB
Java
72 lines
2.2 KiB
Java
package net.zb.examination.ftp;
|
|
|
|
import io.netty.bootstrap.ServerBootstrap;
|
|
import io.netty.channel.ChannelInitializer;
|
|
import io.netty.channel.ChannelOption;
|
|
import io.netty.channel.EventLoopGroup;
|
|
import io.netty.channel.nio.NioEventLoopGroup;
|
|
import io.netty.channel.socket.SocketChannel;
|
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
|
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
|
|
import io.netty.handler.codec.Delimiters;
|
|
import io.netty.handler.codec.string.StringDecoder;
|
|
import io.netty.handler.codec.string.StringEncoder;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import net.zb.examination.ftp.handlers.FtpInBoundHandler;
|
|
|
|
/**
|
|
* <p></p>
|
|
*
|
|
* @author bin.zhang
|
|
* <p/>
|
|
* Revision History:
|
|
* 2020/04/15, 初始化版本
|
|
* @version 1.0
|
|
**/
|
|
@Slf4j
|
|
public class NettyServerRunner {
|
|
|
|
private Integer port;
|
|
|
|
public NettyServerRunner(int port){
|
|
this.port = port;
|
|
}
|
|
|
|
|
|
public void run(){
|
|
EventLoopGroup boss = new NioEventLoopGroup();
|
|
EventLoopGroup work = new NioEventLoopGroup();
|
|
try{
|
|
ServerBootstrap bootstrap = new ServerBootstrap();
|
|
bootstrap.group(boss, work).channel(NioServerSocketChannel.class)
|
|
.childHandler(new ChannelInitializer<SocketChannel>() {
|
|
@Override
|
|
protected void initChannel(SocketChannel socketChannel) {
|
|
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(256, Delimiters.lineDelimiter()));
|
|
socketChannel.pipeline().addLast(new StringDecoder());
|
|
socketChannel.pipeline().addLast(new StringEncoder());
|
|
socketChannel.pipeline().addLast(new FtpInBoundHandler());
|
|
}
|
|
})
|
|
.option(ChannelOption.SO_BACKLOG, 1024)
|
|
.childOption(ChannelOption.SO_KEEPALIVE, true)
|
|
.childOption(ChannelOption.TCP_NODELAY, true);
|
|
bootstrap.bind(port).sync().addListener(future -> {
|
|
if (!future.isSuccess()) {
|
|
future.cause().printStackTrace();
|
|
}
|
|
});
|
|
log.info("ftp服务启动成功, 端口号:{}", port);
|
|
}catch (Exception e){
|
|
log.error("ftp服务启动失败", e);
|
|
}finally {
|
|
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
|
boss.shutdownGracefully().syncUninterruptibly();
|
|
work.shutdownGracefully().syncUninterruptibly();
|
|
}));
|
|
}
|
|
|
|
}
|
|
|
|
}
|