| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package com.qlm.netty;
- import com.qlm.netty.codec.StringDecoder;
- import com.qlm.netty.codec.StringEncoder;
- import com.qlm.netty.handler.NettyServerHandler;
- 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 io.netty.handler.timeout.IdleStateHandler;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.util.concurrent.TimeUnit;
- public class NettyServer {
- private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
- private int port;
- private EventLoopGroup bossGroup;
- private EventLoopGroup workerGroup;
- public NettyServer(int port) {
- this.port = port;
- }
- public void start() throws InterruptedException {
- // 创建两个线程组
- bossGroup = new NioEventLoopGroup(1);
- workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap bootstrap = new ServerBootstrap();
- bootstrap.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class)
- .option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true)
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- protected void initChannel(SocketChannel ch) throws Exception {
- // 添加空闲状态处理器(60秒读取超时)
- ch.pipeline().addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
- // 添加自定义编解码器
- ch.pipeline().addLast(new StringDecoder());
- ch.pipeline().addLast(new StringEncoder());
- // 添加业务处理器
- ch.pipeline().addLast(new NettyServerHandler());
- }
- });
- logger.info("Netty服务端启动成功,监听端口: {}", port);
- ChannelFuture future = bootstrap.bind(port).sync();
- future.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- logger.info("Netty服务端已关闭");
- }
- }
- public void stop() {
- if (workerGroup != null) {
- workerGroup.shutdownGracefully();
- }
- if (bossGroup != null) {
- bossGroup.shutdownGracefully();
- }
- logger.info("Netty服务端已停止");
- }
- }
|