package com.basic.security.utils.socket;
|
|
import android.os.SystemClock;
|
|
import com.basic.security.base.BaseApplication;
|
import com.basic.security.utils.Constants;
|
import com.google.gson.JsonObject;
|
|
import java.io.BufferedInputStream;
|
import java.io.BufferedOutputStream;
|
import java.net.ServerSocket;
|
import java.net.Socket;
|
import java.util.ArrayList;
|
import java.util.LinkedList;
|
import java.util.List;
|
|
public class YuvSocketServer {
|
public static List yuvSocketClientList = new ArrayList();
|
|
public static void startYuvSocketServer() {
|
BaseApplication.getApplication().executorService.execute(() -> {
|
ServerSocket server = null;
|
try {
|
server = new ServerSocket(Constants.yuvServerPort);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
while (true) {
|
try {
|
if (server == null) {
|
break;
|
}
|
Socket client = server.accept();
|
AcceptedClient yuvSocketClient = new AcceptedClient(client);
|
yuvSocketClient.start();
|
// yuvSocketClientList.add(yuvSocketClient);
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
SystemClock.sleep(3000);
|
}
|
}
|
});
|
|
}
|
|
public static class AcceptedClient extends Thread {
|
|
private static final int MAX_BUFFER = 15;
|
private static LinkedList<byte[]> mRgbCameraQueue = new LinkedList<byte[]>();
|
Socket mSocket;
|
|
public AcceptedClient(Socket client) {
|
mSocket = client;
|
}
|
|
public static void addCameraData(byte[] data) {
|
synchronized (mRgbCameraQueue) {
|
if (mRgbCameraQueue.size() == MAX_BUFFER) {
|
mRgbCameraQueue.poll();
|
}
|
mRgbCameraQueue.add(data);
|
}
|
}
|
|
public byte[] getImageBuffer() {
|
byte[] mLastFrame = null;
|
synchronized (mRgbCameraQueue) {
|
if (mRgbCameraQueue.size() > 0) {
|
mLastFrame = mRgbCameraQueue.poll();
|
}
|
}
|
return mLastFrame;
|
}
|
|
@Override
|
public void run() {
|
try {
|
BufferedOutputStream outputStream = new BufferedOutputStream(mSocket.getOutputStream());
|
BufferedInputStream inputStream = new BufferedInputStream(mSocket.getInputStream());
|
JsonObject jsonObj = new JsonObject();
|
jsonObj.addProperty("type", "data");
|
jsonObj.addProperty("length", 460800);
|
jsonObj.addProperty("width", 640);
|
jsonObj.addProperty("height", 480);
|
int rotation = 0;
|
if (Constants.isHuaWeiPad) {
|
rotation = 270;// 华为平板270
|
} else {
|
rotation = 90;
|
}
|
jsonObj.addProperty("rotation", rotation);
|
|
byte[] buff = new byte[256];
|
int len = 0;
|
String msg = null;
|
outputStream.write(jsonObj.toString().getBytes());
|
outputStream.flush();
|
|
while (true) {
|
try {
|
SystemClock.sleep(40); // 一秒发送25张
|
byte[] byteArray = getImageBuffer();
|
if (byteArray == null) {
|
continue;
|
}
|
outputStream.write(byteArray);
|
outputStream.flush();
|
if (Thread.currentThread().isInterrupted())
|
break;
|
} catch (Exception e) {
|
e.printStackTrace();
|
break;
|
}
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
}
|
|
}
|