NettyServer.java 2.3 KB
package com.viontech.netty;

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.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * .
 *
 * @author 谢明辉
 * @date 2020/8/18
 */
@Component
@Slf4j
public class NettyServer implements CommandLineRunner {

    @Value("${netty.port:30001}")
    private int port;

    @Override
    public void run(String[] args) {
        EventLoopGroup workerGroup = new NioEventLoopGroup(30);
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap b = new ServerBootstrap();
            b = b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024 * 1000, 4, 4, -16, 0));
                            ch.pipeline().addLast(new ByteToMessageCodecHandler());
                            ch.pipeline().addLast(new NettyReceiverHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            log.info("通道构建完毕");

            b.bind(port).addListener(future -> {
                if (future.isSuccess()) {
                    log.info("端口[{}]绑定成功", port);
                } else {
                    log.info("端口[{}]绑定失败", port);
                }
            });
        } catch (Exception e) {
            log.error("", e);
        }
    }

}