Mjpeg协议,android创建mjpeg服务请点击参考上篇文章
@Test
public void mjpeg() throws IOException {
byte[] boundary; // 分隔标志
short boundary_index = 0;
byte[] rnrn = new byte[]{'\r', '\n', '\r', '\n'}; // header body分隔标记
short rnrn_index = 0;
boolean start = false;
boolean isJpeg = false;
List<Byte> header = new ArrayList<>(); // 协议头 String类型
ByteBuffer jpeg = null; // 帧数据,数据较大用内存缓存存储
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.1.58:5000/")//169.254.28.64 192.168.62.51
.build();
Response response = client.newCall(request).execute();
// 获取分隔标志
boundary = ("\r\n--" + response.headers().get("Content-Type")
.split(";boundary=")[1]).getBytes();
InputStream inStream = response.body().byteStream();
byte[] buffer = new byte[1024];
int ccc = 0;
//协议开始记录
for (int size = 0; (size = inStream.read(buffer)) != -1; ) {
for (int i = 0; i < size; i++) {
// 数据开始
if (start) {
// 帧数据
if (isJpeg){
if (jpeg == null){
/**
* Content-Type - 1
* Content-Length - 2
*/
String[] info = new String(Tools.listTobyte(header)).split("\r\n");
// jpeg 长度
int length = Integer.valueOf(info[2].split(":")[1].trim());
jpeg = ByteBuffer.allocate(length);
jpeg.put(buffer[i]);
}else {
jpeg.put(buffer[i]);
if (jpeg.position() == jpeg.limit()){
/**
* 数据描述文件 header: List<Byte>
* 每一帧的数据 jpeg: ByteBuffer
*/
// 输出图片
// File file = new File("uploadFile/jpeg"+ccc+".jpg");
// if(!file.exists()){
// file.createNewFile();
// }
// FileOutputStream fe=new FileOutputStream(file,true);
// fe.write(jpeg.array());
// fe.flush();
// fe.close();
/**
* 释放资源,返回捕获状态
*/
isJpeg = false; //退出jpeg状态
start = false; //提出获取数据状态
jpeg.clear();
header.clear();
boundary_index = 0;
rnrn_index = 0;
ccc++;
}
}
}else{
// 验证header结束标识符
if (rnrn_index != 0 && buffer[i] == rnrn[rnrn_index])
rnrn_index++;
// 不符合
else {
rnrn_index = 0;
}
// header结束标识符,检测开始
if (rnrn_index == 0 && buffer[i] == rnrn[0])
rnrn_index++;
header.add(buffer[i]);
// header结束标识符完全通过
if (rnrn_index == rnrn.length) {
isJpeg = true;
}
}
} else {
/**
* 检测开始
*/
// 验证标识符
if (boundary_index != 0 && buffer[i] == boundary[boundary_index])
boundary_index++;
else boundary_index = 0;
// 标识符开始
if (boundary_index == 0 && buffer[i] == boundary[0])
boundary_index++;
// 标识符完全通过,\r\n类型分隔符
if (boundary_index == boundary.length) {
start = true;
} else if (boundary_index == boundary.length) {
log.warn("分隔符错误");
return;
}
}
}
}
inStream.close();
}