0
我試圖把一個簡單的servlet(從另一個源複製)工作。這是一個使用NIO通過ReadListener讀取發佈請求的異步servlet。這是代碼:Java異步NIO servlet現在按預期工作
@WebServlet(name = "AsyncProxyServlet2", urlPatterns = "/*" , asyncSupported = true)
public class AsyncProxyServlet2 extends HttpServlet
{
private static final long serialVersionUID = 8458401860448619054L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
final AsyncContext acontext = request.startAsync();
final ServletInputStream input = request.getInputStream();
System.out.println("request.isAsyncStarted() = " + request.isAsyncStarted() + ", request.isAsyncSupported = " + request.isAsyncSupported() + ", main = " + Thread.currentThread().getName());
input.setReadListener(new ReadListener()
{
byte tmp[] = new byte[4*1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream(this.tmp.length);
@Override
public void onDataAvailable()
{
try
{
System.out.println("onDataAvailable = " + Thread.currentThread().getName());
int numBytesRead = -1;
while (input.isReady() && !input.isFinished())
{
if ((numBytesRead = input.read(this.tmp)) > 0) this.buffer.write(this.tmp, 0, numBytesRead);
}
}
catch (IOException ex) { ex.printStackTrace(); }
}
@Override
public void onAllDataRead()
{
try
{
System.out.println("onAllDataRead = " + Thread.currentThread().getName() + ", buffer size = " + this.buffer.size());
acontext.getResponse().setContentType("text/xml; charset=utf-8");
acontext.getResponse().setContentLength(this.buffer.size());
acontext.getResponse().getOutputStream().write(this.buffer.toByteArray());
}
catch (Exception ex) { ex.printStackTrace(); }
acontext.complete();
}
@Override
public void onError(Throwable t) { t.printStackTrace(); }
});
System.out.println("final 1");
try { Thread.sleep(3000); } catch (Exception e) {}
System.out.println("final 2");
}
}
當我發送POST請求到這個servlet,這段代碼的輸出是:
request.isAsyncStarted() = true, request.isAsyncSupported = true, main = http-nio-80-exec-1
final 1
<-- Here a 3 second pause
final 2
onDataAvailable = http-nio-80-exec-1
onAllDataRead = http-nio-80-exec-1, buffer size = 910
如此看來,一切都在執行同一個線程。直到3秒暫停結束,纔會讀取請求,然後打印最後3條消息。
任何線索爲什麼這不能正常工作?
謝謝。
沒有暫停,結果是一樣的。我的問題是:onDataAvailable和onAlldataRead不應該顯示主線程的另一個不同的線程? – JBalaguero
我不這麼認爲,除非你在其他線程中運行它。 – Xvolks