【发布时间】:2017-03-07 09:06:42
【问题描述】:
我一直在尝试创建一个 MJPEG 服务器,为此,我得到了一个简单的基础服务器 from here。大部分代码都是一样的,只是修改了handle(socket)函数。这是handle(...) 代码-
private void handle(Socket socket) {
try {
...
Read HTTP request... Not needed for MJPEG.
...
// Initial header for M-JPEG.
String header = "HTTP/1.0 200 OK\r\n" +
"Connection: close\r\n" +
"Max-Age: 0\r\n" +
"Expires: 0\r\n" +
"Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0\r\n" +
"Pragma: no-cache\r\n" +
"Content-Type: multipart/x-mixed-replace;boundary=--boundary\r\n\r\n";
output.write(header.getBytes());
// Start the loop for sending M-JPEGs
isStreaming = true;
if (!socket.isClosed()) {
new Thread(new Runnable() {
int id = 1;
@Override
public void run() {
try {
while (isStreaming) {
if (id > 2) id = 1;
byte[] buffer = loadContent(id + ".jpg");
output.write(("--boundary\r\n" +
"Content-Type: image/jpeg\r\n" +
"Content-Length: " + buffer.length + "\r\n").getBytes());
output.write(buffer);
Thread.sleep(1000);
Log.i("Web Server", "Current id: " + id);
id++;
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
output.flush();
output.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我从一些网站获得了标头,并且该服务器在 C++/Linux 中工作(我无法直接移植代码,因为在 C++ 中,我使用了 Qt 的 QTcpServer,这与 SocketServer 有点不同)。
assets 文件夹中有 2 个 JPG,此服务器的工作是显示它们并每秒在它们之间切换。
当我在笔记本电脑的谷歌浏览器上打开这个网站时,我只看到一个白屏(当服务器连接时发生,但没有正确输出数据)。
如果需要任何其他信息,请在 cmets 中询问,我将编辑问题并添加。
谢谢!
【问题讨论】:
标签: java android networking http-headers mjpeg