如何从基于Netty的Httpserver向客户端发送一个以上的响应?
我正在尝试通过netty创建一个httpserver,并且它可以工作。 现在我有一个问题,我可以从Httpserver向客户端发送更多的响应吗? 例如,客户端从Web浏览器请求服务器,服务器在几秒钟后响应“ hello”,然后响应“ bye”。
我添加了三个句柄:
sc.pipeline().addLast(new HttpResponseEncoder());
sc.pipeline().addLast(new HttpRequestDecoder());
sc.pipeline().addLast(new HttpChannelHandler());
在HttpChannelHandler中,我尝试响应两次,但是失败
public class HttpChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
//the content response to the client
String resp_content = "hello";
request = (HttpRequest) msg;
boolean keepaLive = HttpHeaders.isKeepAlive(request);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
OK, Unpooled.copiedBuffer(resp_content.getBytes("UTF-8")));
response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
response.headers().set(CONTENT_LENGTH,
response.content().readableBytes());
if (keepaLive) {
response.headers().set(CONNECTION, KEEP_ALIVE);
//first response
ctx.writeAndFlush(response);
content = "test";
response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
response.headers().set(CONTENT_LENGTH,
response.content().readableBytes());
//second response,but failed
// exception io.netty.util.IllegalReferenceCountException: refCnt: 0
response.content().writeBytes(resp_content.getBytes());
ctx.writeAndFlush(response);
}
}
}
}
答案 0 :(得分:0)
不可能,这是不可能的... HTTP是一种“请求/响应”样式的协议。将响应发送给客户后,您只能在收到另一个请求时再发送一个。