|
@@ -0,0 +1,69 @@
|
|
|
+package com.webchat.connect.netty.config;
|
|
|
+
|
|
|
+
|
|
|
+import com.webchat.connect.netty.handler.NettyWebSocketChannelInitializer;
|
|
|
+import io.netty.bootstrap.ServerBootstrap;
|
|
|
+import io.netty.channel.Channel;
|
|
|
+import io.netty.channel.ChannelFuture;
|
|
|
+import io.netty.channel.ChannelOption;
|
|
|
+import io.netty.channel.EventLoopGroup;
|
|
|
+import io.netty.channel.nio.NioEventLoopGroup;
|
|
|
+import io.netty.channel.socket.nio.NioServerSocketChannel;
|
|
|
+import io.netty.handler.logging.LogLevel;
|
|
|
+import io.netty.handler.logging.LoggingHandler;
|
|
|
+import jakarta.annotation.PreDestroy;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
+import org.springframework.context.event.ContextClosedEvent;
|
|
|
+import org.springframework.context.event.ContextRefreshedEvent;
|
|
|
+import org.springframework.context.event.EventListener;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+//@Configuration
|
|
|
+public class NettyWebSocketServerConfig {
|
|
|
+
|
|
|
+ @Value("${netty.websocket.server.port:9999}")
|
|
|
+ private Integer port;
|
|
|
+
|
|
|
+ private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
|
|
|
+
|
|
|
+ private final EventLoopGroup workerGroup = new NioEventLoopGroup(10);
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 服务端链接管道
|
|
|
+ */
|
|
|
+ private Channel serverChannel;
|
|
|
+
|
|
|
+ @EventListener(ContextRefreshedEvent.class)
|
|
|
+ public void start() throws InterruptedException {
|
|
|
+
|
|
|
+ ServerBootstrap bootstrap = new ServerBootstrap();
|
|
|
+ bootstrap.group(bossGroup, workerGroup)
|
|
|
+ .channel(NioServerSocketChannel.class)
|
|
|
+ .handler(new LoggingHandler(LogLevel.INFO))
|
|
|
+ // 业务自定义handler链
|
|
|
+ .childHandler(new NettyWebSocketChannelInitializer())
|
|
|
+ .option(ChannelOption.SO_BACKLOG, 1024)
|
|
|
+ .childOption(ChannelOption.SO_KEEPALIVE, true);
|
|
|
+
|
|
|
+ ChannelFuture future = bootstrap.bind(port).sync();
|
|
|
+ serverChannel = future.channel();
|
|
|
+ log.info("Netty WebSocket Server started on port {}", port);
|
|
|
+ }
|
|
|
+
|
|
|
+ @PreDestroy
|
|
|
+ @EventListener(ContextClosedEvent.class)
|
|
|
+ public void stop() {
|
|
|
+ if (serverChannel == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ serverChannel.close();
|
|
|
+ if (!bossGroup.isShutdown()) {
|
|
|
+ bossGroup.shutdownGracefully();
|
|
|
+ }
|
|
|
+ if (!workerGroup.isShutdown()) {
|
|
|
+ workerGroup.shutdownGracefully();
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|