66 lines
2.5 KiB
Java
Raw Normal View History

2024-01-09 15:52:26 +08:00
package com.zhgd.netty.tcp.server;
2023-03-08 19:34:48 +08:00
2024-01-09 15:52:26 +08:00
import com.zhgd.netty.tcp.handler.TcpNettyHandler;
import com.zhgd.netty.tcp.listener.BindListener;
import com.zhgd.netty.tcp.listener.CloseListener;
2023-03-08 19:34:48 +08:00
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;
2023-04-04 14:45:10 +08:00
import lombok.extern.slf4j.Slf4j;
2023-03-08 19:34:48 +08:00
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
2023-04-04 14:45:10 +08:00
@Slf4j
2023-03-08 19:34:48 +08:00
public class TcpNettyServer {
@Autowired
private TcpNettyHandler tcpNettyHandler;
2023-03-13 16:19:58 +08:00
@Value("${high_formwork.netty.port:15333}")
2023-03-08 19:34:48 +08:00
int port;
@PostConstruct
private void startTcpServer() {
2023-04-04 14:45:10 +08:00
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<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//添加自定义处理器
socketChannel.pipeline()
2023-08-02 09:59:40 +08:00
//.addLast(new StringEncoder(StandardCharsets.UTF_8))
//.addLast(new StringDecoder(Charset.forName("GBK")))
2023-04-04 14:45:10 +08:00
.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();
}
2023-03-08 19:34:48 +08:00
}
}