NettyServer.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.qlm.netty;
  2. import com.qlm.netty.codec.StringDecoder;
  3. import com.qlm.netty.codec.StringEncoder;
  4. import com.qlm.netty.handler.NettyServerHandler;
  5. import io.netty.bootstrap.ServerBootstrap;
  6. import io.netty.channel.ChannelFuture;
  7. import io.netty.channel.ChannelInitializer;
  8. import io.netty.channel.ChannelOption;
  9. import io.netty.channel.EventLoopGroup;
  10. import io.netty.channel.nio.NioEventLoopGroup;
  11. import io.netty.channel.socket.SocketChannel;
  12. import io.netty.channel.socket.nio.NioServerSocketChannel;
  13. import io.netty.handler.timeout.IdleStateHandler;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. import java.util.concurrent.TimeUnit;
  17. public class NettyServer {
  18. private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
  19. private int port;
  20. private EventLoopGroup bossGroup;
  21. private EventLoopGroup workerGroup;
  22. public NettyServer(int port) {
  23. this.port = port;
  24. }
  25. public void start() throws InterruptedException {
  26. // 创建两个线程组
  27. bossGroup = new NioEventLoopGroup(1);
  28. workerGroup = new NioEventLoopGroup();
  29. try {
  30. ServerBootstrap bootstrap = new ServerBootstrap();
  31. bootstrap.group(bossGroup, workerGroup)
  32. .channel(NioServerSocketChannel.class)
  33. .option(ChannelOption.SO_BACKLOG, 128)
  34. .childOption(ChannelOption.SO_KEEPALIVE, true)
  35. .childHandler(new ChannelInitializer<SocketChannel>() {
  36. @Override
  37. protected void initChannel(SocketChannel ch) throws Exception {
  38. // 添加空闲状态处理器(60秒读取超时)
  39. ch.pipeline().addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
  40. // 添加自定义编解码器
  41. ch.pipeline().addLast(new StringDecoder());
  42. ch.pipeline().addLast(new StringEncoder());
  43. // 添加业务处理器
  44. ch.pipeline().addLast(new NettyServerHandler());
  45. }
  46. });
  47. logger.info("Netty服务端启动成功,监听端口: {}", port);
  48. ChannelFuture future = bootstrap.bind(port).sync();
  49. future.channel().closeFuture().sync();
  50. } finally {
  51. workerGroup.shutdownGracefully();
  52. bossGroup.shutdownGracefully();
  53. logger.info("Netty服务端已关闭");
  54. }
  55. }
  56. public void stop() {
  57. if (workerGroup != null) {
  58. workerGroup.shutdownGracefully();
  59. }
  60. if (bossGroup != null) {
  61. bossGroup.shutdownGracefully();
  62. }
  63. logger.info("Netty服务端已停止");
  64. }
  65. }