Netty Socket 端口如何禁止 HTTP 请求
在 Netty 中,可以通过如下方式禁止 HTTP 请求:
- 实现自定义的 ChannelHandler,用于过滤 HTTP 请求,只允许处理非 HTTP 请求。
例如:
public class NonHttpServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
// 拒绝 HTTP 请求
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
Unpooled.copiedBuffer('Unsupported Protocol', CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, 'text/plain; charset=UTF-8');
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
return;
}
// 处理非 HTTP 请求
// ...
}
}
- 在 Netty 的服务启动代码中,将自定义的 ChannelHandler 添加到 ChannelPipeline 中。
例如:
public class NettyServer {
public void start() {
// 创建 ServerBootstrap
ServerBootstrap bootstrap = new ServerBootstrap();
// ...
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 添加自定义的 ChannelHandler
pipeline.addLast(new NonHttpServerHandler());
// ...
}
});
// ...
}
}
通过以上方式,在 Netty 的 Socket 端口上可以禁止 HTTP 请求,只允许处理非 HTTP 请求。
原文地址: https://www.cveoy.top/t/topic/m8zA 著作权归作者所有。请勿转载和采集!