我正在尝试用Java创建一个简单的视频流。我得到了一些mp4视频,但不是全部。另一方面,我无法在视频播放时寻找视频流(在VLC和Chrome中尝试)。我想知道:我的代码有什么问题?
以下是代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Xerver {
protected void start() {
ServerSocket s;
Socket remote;
OutputStream out;
System.out.println("Webserver starting up on port 8080");
try {
// create the main server socket
s = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
FileInputStream fs;
out = remote.getOutputStream();
File file = new File("D:\\stream.mp4");
out.write("HTTP/1.0 200 OK\r\n".getBytes());
out.write("Content-Type: video/mp4\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(String.format("Content-Length:%s\r\n\r\n",Long.toString(file.length())).getBytes());
fs = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int count = 0;
do{
count = fs.read(buffer);
out.write(buffer, 0, count);
}
while (count <= 1024);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
Xerver ws = new Xerver();
ws.start();
}
}
提前致谢