package com.zhentao.information.config; import com.zhentao.information.handler.WebSocketHandler; import io.netty.bootstrap.ServerBootstrap; 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.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** * Netty服务器配置类 * 配置WebSocket服务器的启动参数和处理器链 */ @Slf4j @Configuration public class NettyConfig { /** * WebSocket服务器端口 */ @Value("${netty.websocket.port}") private int port; /** * WebSocket消息处理器 */ @Resource private WebSocketHandler webSocketHandler; /** * 配置并启动Netty服务器 * @return ServerBootstrap实例 */ @Bean public ServerBootstrap serverBootstrap() { // 创建主从线程组 // bossGroup用于接收客户端连接 EventLoopGroup bossGroup = new NioEventLoopGroup(1); // workerGroup用于处理客户端数据 EventLoopGroup workerGroup = new NioEventLoopGroup(); // 创建服务器启动对象 ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) // 设置服务器通道实现 .channel(NioServerSocketChannel.class) // 设置线程队列等待连接个数 .option(ChannelOption.SO_BACKLOG, 128) // 设置保持活动连接状态 .childOption(ChannelOption.SO_KEEPALIVE, true) // 禁用Nagle算法,减少延迟 .childOption(ChannelOption.TCP_NODELAY, true) // 设置处理器 .childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) { // 获取管道 ch.pipeline() // HTTP编解码器 .addLast(new HttpServerCodec()) // 支持大数据流 .addLast(new ChunkedWriteHandler()) // HTTP消息聚合器 .addLast(new HttpObjectAggregator(65536)) // 调整心跳检测时间:30秒没有收到消息就触发 .addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS)) // WebSocket协议处理器 .addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536)) // 自定义消息处理器 .addLast(webSocketHandler); } }); try { // 绑定端口并启动服务器 bootstrap.bind(port).sync(); log.info("Netty WebSocket服务器启动成功,端口:{}", port); } catch (InterruptedException e) { log.error("Netty WebSocket服务器启动失败", e); Thread.currentThread().interrupt(); } return bootstrap; } }