显然,doGet
方法的返回类型为 void,因此,它不返回任何内容。从这个意义上说,我使用“返回”一词来表示将响应发送回请求它的客户端。
我正在尝试实现一个长轮询 Servlet。在我有想要发回的内容之前不发送响应是有益的。因此,在 doGet 方法中,我将连接的用户 ID 和 AsyncContext 添加到映射中:
private ConcurrentMap<String, AsyncContext> contexts = new ConcurrentHashMap<>();
//...in the doGet method when I need to add the context...
contexts.put(userId, context);
然后,当我有东西要发回时,我可以检索适当的上下文并写入其响应输出流:
AsyncContext context = contexts.get(userId);
PrintWriter writer = context.getResponse().getWriter();
writer.write("something to send to the client");
但是,客户似乎从未收到回复。查看浏览器开发者控制台中的“网络”选项卡,我可以看到 GET 请求已发送,然后返回(状态为 200)。这发生在我实际寄回东西之前。这让我相信 doGet 方法完成后会返回响应。也许正因为如此,在此之后,由于连接未打开,因此无法向客户端发送任何内容。
doGet 方法执行完成后是否将响应发送给客户端?如果是这种情况,如何保持连接打开以获得长轮询效果?
回答我自己的问题:Does the doGet method send the response to the client once the method is finished executing?
是的,当 doGet (或任何 HttpServlet 方法,例如:doGet、doPost 等)方法完成执行时,它将响应发送回客户端。
If this is the case, how can I keep the connection open for a long-polling effect?
使用异步 Servlet(我正在使用它,但是,我发现我的特定问题一定在其他地方,但这些答案仍然与所提出的问题相关)。在 ServletRequest 对象上调用 startAsync 方法,如下所示:
AsyncContext context = request.startAsync(request, response);
“这将通知 Web 容器,在请求调用结束时,它应该释放处理线程并保持连接打开,以便其他线程写入响应并结束连接。”参考链接。
另外,我将添加针对我的特定问题(客户端未收到响应)的解决方案,因为在我的 Servlet 中,我没有调用 AsyncContext 对象上的完整方法:
asyncContext.complete();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)