package com.zhgd.netty.tcp.server; import com.zhgd.netty.tcp.handler.TcpNettyHandler; import com.zhgd.netty.tcp.listener.BindListener; import com.zhgd.netty.tcp.listener.CloseListener; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; 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 lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @author chenws * @date 2020/03/17 15:45:35 */ @Component @Slf4j public class TcpNettyServer { @Autowired private TcpNettyHandler tcpNettyHandler; @Value("${high_formwork.netty.port:15333}") int port; @PostConstruct private void startTcpServer() { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(6); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //添加自定义处理器 socketChannel.pipeline() //.addLast(new StringEncoder(StandardCharsets.UTF_8)) //.addLast(new StringDecoder(Charset.forName("GBK"))) .addLast(tcpNettyHandler); } }); //监听器,当服务绑定成功后执行 ChannelFuture channelFuture = serverBootstrap.bind(port).addListener(new BindListener()); //监听器,当停止服务后执行。 channelFuture.channel().closeFuture().addListener(new CloseListener()); } catch (Exception e) { log.error("err:", e); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }