简体   繁体   English

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

[英]How can I send more then one response to client from a Httpserver base on Netty

How can I send more then one response to client from a Httpserver base on Netty? 如何从Netty上的Httpserver基站向客户端发送多个响应?

I am trying to make a httpserver by netty and it works. 我试图通过netty创建一个httpserver,它可以工作。 Now I have a question,can I send more then one response to client from a Httpserver ? 现在我有一个问题,我可以从Httpserver向客户端发送多个响应吗? For example, the client requests the server from a web browser, and server responses "hello" then responses "bye" several seconds later. 例如,客户端从Web浏览器请求服务器,服务器响应“hello”然后在几秒钟后响应“bye”。

I add three handles: 我添加了三个句柄:

    sc.pipeline().addLast(new HttpResponseEncoder());
    sc.pipeline().addLast(new HttpRequestDecoder());
    sc.pipeline().addLast(new HttpChannelHandler());

In the HttpChannelHandler ,I tried to response twice,but failed 在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);
            }
        }
    }
}

No thats not possible... HTTP is a "request/response" style protocol. 不可能...... HTTP是一种“请求/响应”式协议。 Once you sent a response to the client you can only send another one when you receive another request. 一旦您向客户发送了回复,您只能在收到另一个请求时发送另一个回复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM