我用Java编写了一个http服务器已经有一段时间了(差不多两年了?)而且我仍然遇到让字节范围请求工作的问题。我只使用套接字的输入和输出流进行原始字节数据传输(即文件下载/上传),并使用PrintWriter
将响应头/字符串发送到连接客户端(例如{{1}等等)。
我不想使用任何servlet或apis(例如HTTPURLConnection或其他)。我想这样做"香草风格"。
我可以非常快速地提供正常的网页(例如文件浏览,上传和下载,看电影,听音乐,查看pdf文件,文本,图片,gif文件等),这样就可以了不是问题。
但是,每当我尝试实现字节范围请求时,服务器都会完美地接收客户端的请求,解析给定的数据,准备文件输入流以进行发送,然后当我将数据发送到客户端时,客户端总是放弃与HTTP/1.1 200 OK
的连接。(我需要字节范围请求,例如:观看一小时长的视频,然后dang wifi信号丢失,你不想重新观看整个来自方块1的视频,恢复暂停下载'等等。)
这真让我难过,我确实在搜索服务字节范围请求的java示例,当我尝试实现它们时,所有这些都失败了。我甚至尝试从头开始测试,并产生相同的结果。以下是与我要完成的内容相关的代码片段:
发送和接收普通网页(工作正常,这是一个例子):
software caused connection abort: socket write error
字节范围服务(在解析客户端请求数据之后):
...
OutputStream outStream = client.getOutputStream();
PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8), true);
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html; charset=\"UTF-8\"");
String responseStr = "<!DOCTYPE html><html><head><title>Hello, world!</title></head><body><string>This is a simple example webpage!</string></body></html>";
if(acceptEncoding.contains("gzip") && responseStr.length() > 33) {
out.println("Content-Encoding: gzip");
byte[] r = StringUtil.compressString(responseStr, "UTF-8");
out.println("Content-Length: " + r.length);
out.println("");
if(protocol.equalsIgnoreCase("GET")) {
outStream.write(r);
}
} else {
out.println("Content-Length: " + responseStr.length());
out.println("");
if(request.protocol.equalsIgnoreCase("GET")) {
out.println(responseStr);
}
}
out.flush();
//followed by closing resources, etc.
...
对于任何感兴趣的人,运行在这个基本代码上的服务器在redsandbox.no-ip.org(指向我的服务器)上联机,目前我已用public static final long copyInputStreamToOutputStream(InputStream input, OutputStream output, long startBytes, long endBytes) throws IOException {
byte[] buffer = new byte[20480];//1024
long count = 0;
int read;
input.skip(startBytes);
long toRead = (endBytes - startBytes) + 1;
while((read = input.read(buffer)) > 0) {
if((toRead -= read) > 0) {
output.write(buffer, 0, read);//Socket error happens on this line mostly
output.flush();
} else {
output.write(buffer, 0, (int) toRead + read);//but also on this line sometimes
output.flush();
break;
}
count += read;
}
return count;
}
禁用字节请求而不是Accept-Ranges: none
,但我可以再次打开它进行测试。
如果我需要添加更多代码,请告诉我们!感谢您的时间。 或者,如果您希望完整查看我的服务器代码,可以在github上查看: https://github.com/br45entei/JavaWebServer
答案 0 :(得分:2)
这个读写循环是否正常工作,确实看起来简化了?这不在我的脑海中,因此可能会发现轻微的语法错误。我期待startIdx + endIdx都是包容性指标。
public static final long copyInputToOutput(InputStream input, OutputStream output, long startIdx, long endIdx) throws IOException {
final long maxread = 24*1024;
byte[] buffer = new byte[(int)maxread];
input.skip(startIdx);
long written=0;
long remaining = endIdx-startIdx+1;
while(remaining>0) {
int read = input.read(buffer, 0, (int)Math.min(maxread, remaining));
output.write(buffer, 0, read);
remaining -= read;
written += read;
}
output.flush();
return written;
}
答案 1 :(得分:1)
所以我想出了我的问题,部分归功于Whome。首先,我没有向客户端发送正确的Content-Length:
标头,其次,我的endbytes
变量计算错误。这是工作代码:
public static final long copyInputStreamToOutputStream(InputStream input, OutputStream output, long startBytes, long endBytes, final long contentLength, boolean debug) throws IOException {
byte[] buffer = new byte[20480];//1024
long count = 0;
int read;
long skipped = input.skip(startBytes);//I tested this quite a few times with different files and it does indeed skip the desired amount of bytes.
final long length = (endBytes - startBytes) + 1;
if(debug) {
println("Start bytes: " + startBytes + "; End bytes: " + endBytes + "; Skipped bytes: " + skipped + "; Skipped equals startBytes: " + (skipped == startBytes) + "; Length: " + length + "; Total file size: " + contentLength);
}
long toRead = length;
while((read = input.read(buffer)) != -1) {
count += read;
long bytesLeft = length - count;
if(debug) {
println("read: " + read + "; toRead: " + toRead + "; length: " + length + "; count: " + count + "; bytesLeft: " + bytesLeft);
}
toRead -= read;
if(bytesLeft >= buffer.length) {//Changed the if statement here so that we actually send the last amount of data to the client instead of whatever is leftover in the buffer
output.write(buffer, 0, read);
output.flush();
} else {
output.write(buffer, 0, read);//Send the currently read bytes
output.flush();
bytesLeft = length - count;//recalculate the remaining byte count
read = input.read(buffer, 0, (int) bytesLeft);//read the rest of the required bytes
count += read;
if(debug) {
println("[Last one!]read: " + read + "; toRead: " + toRead + "; length: " + length + "; count: " + count + "; bytesLeft: " + bytesLeft);
}
output.write(buffer, 0, read);//and send them over
output.flush();
break;
}
}
return count;
}
由于我的endBytes
变量比我需要的多一个,我试图通过调整它周围的代码来进行补偿。但是,我需要简单地从中减去一个。带有buffer.length
的if语句是为了确保将最后一个字节发送到客户端。在没有它的测试中,客户端(谷歌浏览器)挂起并等待剩余的字节,但从未接收到它们,然后当30秒超时关闭连接时,网页重置。我还没有用其他浏览器来测试它,但我认为它应该可行。