如何从Netty上的Httpserver基站向客户端发送多个响应

问题描述 投票:0回答:1

如何从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);
            }
        }
    }
}
java netty httpserver
1个回答
0
投票

不可能...... HTTP是一种“请求/响应”式协议。一旦您向客户发送了回复,您只能在收到另一个请求时发送另一个回复。

© www.soinside.com 2019 - 2024. All rights reserved.