我正在尝试从自定义视频源对象流式传输 M-JPEG 内容,但是在查看来自 Wireshark 的连接时,没有从服务器返回任何数据。以下是我使用的一些相关代码段。有谁知道如何让这段代码发挥作用?
部分:
try {
server = new HTTPServerWrapper(8099);
server.MJpegBindVideoSource(camera, "/test");
} catch (IOException ex) {
Logger.getLogger(Recorder.class.getName()).log(Level.SEVERE, null, ex);
}
物理/服务器/HTTPServerWrapper.java:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package physics.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import physics.VideoSource;
/**
*
* @author rritoch
*/
public class HTTPServerWrapper {
com.sun.net.httpserver.HttpServer server;
public HTTPServerWrapper(int port) throws IOException{
server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(port), 0);
}
public void MJpegBindVideoSource(VideoSource vs, String path) {
final VideoSource v = vs;
server.createContext(path,new MJpegHandler(vs));
}
}
物理/服务器/MJpegHandler.java:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package physics.server;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import physics.VideoSource;
/**
*
* @author rritoch
*/
public class MJpegHandler implements HttpHandler {
VideoSource vs;
public MJpegHandler(VideoSource videosource) {
this.vs = videosource;
}
public void setVideoSource(VideoSource videosource) {
this.vs = videosource;
}
public void handle(HttpExchange connection) throws IOException {
byte[] data;
System.err.println("Connect...");
String boundary = "VNetPhysics";
Headers responseHeaders = connection.getResponseHeaders();
responseHeaders.add("Content-Type", String.format("multipart/x-mixed-replace; boundary=--%s", boundary));
responseHeaders.add("Cache-Control", "no-cache, private");
responseHeaders.add("Pragma", "no-cache");
responseHeaders.add("Max-Age", "0");
responseHeaders.add("Expires", "0");
connection.sendResponseHeaders(200, 0);
OutputStream responseBody = connection.getResponseBody();
while (true) {
BufferedImage bufferedImage = vs.getBufferedImage();
ByteArrayOutputStream os = new ByteArrayOutputStream(8192 * 4);
ImageIO.write(bufferedImage, "jpg", os);
data = os.toByteArray();
os.close();
responseBody.write(("--" + boundary + "\r\n"
+ "Content-type: image/jpg\r\n"
+ "Content-Length: "
+ data.length
+ "\r\n\r\n").getBytes());
responseBody.write(data);
responseBody.flush();
}
}
};
编辑:将连接消息添加到 stderr 后,似乎对 http://192.168.2.7:8099/test 的请求没有被定向到这个处理程序,没有处理程序我可以看到它为什么不起作用。为了让这个处理程序处理请求,我缺少什么?