我正在写一个音乐网络应用程序,一个servlet处理mp3请求,首先我播放mp3,正确播放,然后暂停,然后恢复,我得到一个ClientAbortException,我的容器是tomcat7。我不知道我错了什么,请给我一些帮助。谢谢!
@WebServlet("/mp3")
public class Mp3Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Path path = Paths.get("/Users/jiangxingshang/Documents/workspace/eclipse/MyMusic/my-music/src/main/webapp/assets/sound/1.mp3");
try (
SeekableByteChannel input = Files.newByteChannel(path, StandardOpenOption.READ);
WritableByteChannel output = Channels.newChannel(resp.getOutputStream())) {
String range = req.getHeader("range");
int pos = 0;
if(StringUtils.isNotEmpty(range)) {
String[] tmp = StringUtils.removeStart(range, "bytes=").split("-");
try {
pos = Integer.valueOf(tmp[0]);
input.position(pos);
} catch(NumberFormatException ignore) {
pos = 0;
}
}
System.out.println("start position: " + pos);
int len = (int)Files.size(path);
resp.addHeader("Accept-Ranges", "bytes");
resp.addHeader("Connection", "Keep-Alive");
resp.addHeader("Content-Range", String.format("bytes %d-%d/%d", pos, len - 1, len));
resp.addHeader("Keep-Alive", "timeout=2, max=100");
resp.addDateHeader("Last-Modified", Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS).toMillis());
resp.setContentType("audio/mpeg");
resp.setContentLength(len);
ByteBuffer bb = ByteBuffer.allocate(2048);
while(input.read(bb) != -1) {
bb.flip();
output.write(bb);
bb.clear();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
两次请求标头,我已删除Cookie和User-Agent标头信息。
首先播放
host: localhost:8080
connection: keep-alive
pragma: no-cache
cache-control: no-cache
accept-encoding: identity;q=1, *;q=0
accept: */*
accept-language: ja,en-US;q=0.8,en;q=0.6,zh;q=0.4
range: bytes=0-
----------------------------------------------------------------------
start position: 0
简历时
host: localhost:8080
connection: keep-alive
pragma: no-cache
cache-control: no-cache
accept-encoding: identity;q=1, *;q=0
accept: */*
accept-language: ja,en-US;q=0.8,en;q=0.6,zh;q=0.4
range: bytes=229376-
----------------------------------------------------------------------
start position: 229376