Springboot+Netty实现http和ws统一端口处理
package com.example.config;
import com.example.netty.MyHttpHandler;
import com.example.netty.MyTextWebSocketFrameHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
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.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NettyConfiguration {
@Bean(destroyMethod = "shutdownGracefully")
public EventLoopGroup bossGroup() {
return new NioEventLoopGroup();
}
@Bean(destroyMethod = "shutdownGracefully")
public EventLoopGroup workerGroup() {
return new NioEventLoopGroup();
}
@Bean
public ServerBootstrap serverBootstrap() {
return new ServerBootstrap();
}
@Bean
public Channel serverChannel(EventLoopGroup bossGroup, EventLoopGroup workerGroup, ServerBootstrap serverBootstrap) {
return serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
// Add more configuration here, like child handlers for HTTP and WebSocket
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 跨域配置
CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
ch.pipeline().addLast(new CorsHandler(corsConfig));
ch.pipeline().addLast(new HttpServerCodec()); // HTTP 编解码
ch.pipeline().addLast(new ChunkedWriteHandler()); // 支持大文件传输
ch.pipeline().addLast(new HttpObjectAggregator(65536)); // HTTP 消息聚合
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws")); // WebSocket 协议处理
ch.pipeline().addLast(new MyTextWebSocketFrameHandler()); // WebSocket 文本帧处理
ch.pipeline().addLast(new MyHttpHandler()); // HTTP 请求处理
}
})
.bind(8080).syncUninterruptibly().channel();
}
}