Luc*_*ano 5 java servlets servlet-3.1
假设我正在写一大块数据HttpServletResponse.所以我的方法接收一个字节数组,我写它response.getOutputStream(),然后我释放线程.当我收到另一块数据时,我的方法将被唤醒,它将getOutputStream()再次写入.最后,我打电话给AsyncContext.complete().
现在,WriteListener.onWritePossible()规范说:
第一次可以写入数据时,容器将调用此方法.当且仅当ServletOutputStream上的isReady方法(如下所述)返回false时,容器才会调用onWritePossible方法.
似乎当容器调用此方法时,我已经需要在某处缓冲我的响应,因为onWritePossible()可能永远不会再次调用.所以,对于前面的例子,我需要在缓冲区中写入我收到的所有数据块(一个字节数组,如果缓冲区足够大,可能是一个临时文件),如果onWritePossible()在我的响应完成之前调用,那么应该怎样我做?阻止线程,直到我有我的所有响应数据?
嗯..维护缓冲区似乎是方法
public void onWritePossible() throws IOException {
doWrite();
}
// this is some callback where you received next chunk of data
public void onMoreDataReceived(byte[] data) {
putDataToBuffer(data);
doWrite();
}
// this method is non-blocking
private void synchronized doWrite() throws IOException {
while (_servletOutputStream.isReady() && hasMoreDataInBuffer()) {
_servletOutputStream.write(getMoreBytesFromBuffer());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1018 次 |
| 最近记录: |