zhangzengfei
2022-01-10 4496b59ab27d569df1da7ef634e02273b3a9618a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package com.basic.security.utils;
 
import android.os.SystemClock;
 
import com.basic.security.manager.OfficeDeviceManager;
import com.basic.security.utils.yuv.BitmapListener;
import com.basic.security.utils.yuv.YuvToJpgFrameBufferManager;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
 
public class SocketUtil {
 
    public ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    public Socket socket = null;
    public byte[] buffer = new byte[1];
    //    public BufferedInputStream inputStream;
//    public BufferedOutputStream outputStream;
    public DataInputStream dataInputStream;
    public DataOutputStream dataOutStream;
    public ObjectOutputStream objectOutputStream;
    public ObjectInputStream objectInputStream;
    public YuvToJpgFrameBufferManager mBufferManager;
    public byte[] imageBuff;
    public String remoteIp = "";
    public String deviceId = "";
    boolean useJson = true;
 
    public SocketUtil() {
    }
 
    public Map<String, String> readJsonAsMap() throws Exception {
        String json = null;
        int len = 0;
        while ((len = dataInputStream.read(buffer)) != -1) {
            for (int i = 0; i < len; i++) {
                if (buffer[i] == '\0') {
                    Map<String, String> messageMap = new HashMap<>();
                    try {
                        byte[] jsonByteArray = byteArrayOutputStream.toByteArray();
                        byteArrayOutputStream.reset();
                        json = new String(jsonByteArray, 0, jsonByteArray.length);
                        json = json.substring(0, json.lastIndexOf("}") + 1);
                        if (json.length() > 3) {
//                            System.out.println(FrameUtil.getFrames("Client")+" json="+json);
                            JsonParser parser = new JsonParser();
                            boolean isJSON = true;
                            JsonElement element = null;
                            try {
                                element = parser.parse(json);
                            } catch (JsonParseException e) {
                                System.out.println("exception: " + e);
                                isJSON = false;
                            }
                            if (isJSON && element != null) {
                                JsonObject obj = element.getAsJsonObject();
                                for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
                                    if (!(entry.getValue() instanceof JsonNull)) {
                                        messageMap.put(entry.getKey(), entry.getValue().getAsString());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return messageMap;
                } else {
                    byteArrayOutputStream.write(buffer[i]);
                }
            }
        }
        throw new RuntimeException("inputStream.read(buffer) == -1");
    }
 
    public void close() {
        try {
//            if (outputStream != null) {
//                outputStream.close();
//                outputStream = null;
//            }
//            if (inputStream != null) {
//                inputStream.close();
//                inputStream = null;
//            }
            if (socket != null) {
                socket.close();
                socket = null;
            }
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
                byteArrayOutputStream = null;
            }
            if (mBufferManager != null) {
                mBufferManager.close();
                mBufferManager = null;
            }
        } catch (IOException e) {
        }
    }
 
    public void setSocket(Socket socket) throws Exception {
        this.socket = socket;
//        socket.setSoTimeout(10*1000);
        this.remoteIp = (((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()).toString().replace("/", "");
        ;
 
        BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
        BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
        dataInputStream = new DataInputStream(socket.getInputStream());
        dataOutStream = new DataOutputStream(outputStream);
        if (byteArrayOutputStream == null) {
            byteArrayOutputStream = new ByteArrayOutputStream();
        }
        byteArrayOutputStream.reset();
    }
 
    public void openSocket(String ip, int port) throws Exception {
//        System.out.println("SocketUtil.openSocket " + FrameUtil.getFrames("Client"));
        close();
        SystemClock.sleep(Constants.reconnectInMilliSeconds);
        socket = new Socket();
//        socket.setSoTimeout(10*1000);
        socket.connect(new InetSocketAddress(ip, port), 10000);
        this.setSocket(socket);
    }
 
//    public void writeEmptyMessage() throws Exception {
//        outputStream.write('\0');
//        outputStream.flush();
//    }
 
    public void writeMessage(String key, String value) throws Exception {
        if (useJson) {
            JsonObject jsonObj = new JsonObject();
            jsonObj.addProperty(key, value);
            dataOutStream.write(jsonObj.toString().getBytes());
            dataOutStream.write('\0');
            dataOutStream.flush();
        } else {
//            JsonObject jsonObj = new JsonObject();
//            jsonObj.addProperty(key, value);
//            outputStream.write(jsonObj.toString().getBytes());
//            outputStream.write('\0');
//            outputStream.flush();
        }
    }
 
    public void writeMessage(Map<String, String> keyValues) throws Exception {
        JsonObject jsonObj = new JsonObject();
        for (Map.Entry<String, String> entry : keyValues.entrySet()) {
            jsonObj.addProperty(entry.getKey(), entry.getValue());
        }
//        System.out.println("SocketUtil.writeMessage json="+jsonObj);
        dataOutStream.write(jsonObj.toString().getBytes());
        dataOutStream.write('\0');
        dataOutStream.flush();
    }
 
    public void writeByteArray(byte[] byteArray) throws Exception {
        if (byteArray != null) {
            dataOutStream.write(byteArray);
            dataOutStream.flush();
        }
    }
 
    public void readFullByteArray(byte[] imageBuff) throws Exception {
//        if (dataInputStream == null) {
//            dataInputStream = new DataInputStream(inputStream);
//        }
        dataInputStream.readFully(imageBuff, 0, imageBuff.length);
    }
 
    public void readFrameInfo() throws Exception {
        Map<String, String> messageMap = this.readJsonAsMap();
        int length = Integer.parseInt(messageMap.get("length"));
        int width = Integer.parseInt(messageMap.get("width"));
        int height = Integer.parseInt(messageMap.get("height"));
        imageBuff = new byte[length];
        mBufferManager = new YuvToJpgFrameBufferManager(length, width, height);
    }
 
    public boolean readBitmapHeader(Map<String, String> frameInfo) {
        boolean success = frameInfo.get(Constants.SUCCESS).equals(Constants.TRUE);
        if (success) {
            int length = Integer.parseInt(frameInfo.get("length"));
            int width = Integer.parseInt(frameInfo.get("width"));
            int height = Integer.parseInt(frameInfo.get("height"));
            imageBuff = new byte[length];
            mBufferManager = new YuvToJpgFrameBufferManager(length, width, height);
        }
        return success;
    }
 
    public boolean readBitmapHeader() throws Exception {
 
        return readBitmapHeader((Map<String, String>) this.readObject());
    }
 
    public void setBitmapListener(BitmapListener cameraDataListener) {
        mBufferManager.setOnDataListener(cameraDataListener);
    }
 
    public void readFrames(BitmapListener cameraDataListener) throws Exception {
        readFrameInfo();
        setBitmapListener(cameraDataListener);
        while (!Thread.currentThread().isInterrupted()) {
            this.readFullByteArray(imageBuff);
            mBufferManager.fillBuffer(imageBuff, imageBuff.length);
        }
    }
 
    public void readFrame(BitmapListener yuvToJpgFrameListener) throws Exception {
        readFrameInfo();
        setBitmapListener(yuvToJpgFrameListener);
        while (!Thread.currentThread().isInterrupted()) {
            this.readFullByteArray(imageBuff);
            mBufferManager.fillBuffer(imageBuff, imageBuff.length);
            break;
        }
    }
 
    public void writeFrameInfo() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("type", "data");
        map.put("length", "460800");
        map.put("width", "640");
        map.put("height", "480");
        map.put("rotation", (Constants.isHuaWeiPad ? 270 : 90) + "");
        this.writeMessage(map);
    }
 
    public Map<String, String> getFrameInfo() {
        Map<String, String> frameInfo = new HashMap<>();
        frameInfo.put("type", "data");
        frameInfo.put("length", "460800");
        frameInfo.put("width", "640");
        frameInfo.put("height", "480");
        frameInfo.put("rotation", (Constants.isHuaWeiPad ? 270 : 90) + "");
        return frameInfo;
    }
 
 
    public void writeObject(Object object) throws Exception {
        if (useJson) {
            writeMessage((Map<String, String>) object);
        } else {
//            if (objectOutputStream == null) {
//                objectOutputStream = new ObjectOutputStream(outputStream);
//            }
//            objectOutputStream.writeObject(object);
//            objectOutputStream.flush();
        }
    }
 
 
    public void writeOneBitmap(Object object) throws Exception {
        if (useJson) {
            writeByteArray((byte[]) object);
        } else {
//            if (objectOutputStream == null) {
//                objectOutputStream = new ObjectOutputStream(outputStream);
//            }
//            objectOutputStream.writeObject(object);
//            objectOutputStream.flush();
        }
    }
 
    public void readObject(BitmapListener cameraDataListener) throws Exception {
        readFrameInfo();
        setBitmapListener(cameraDataListener);
        while (!Thread.currentThread().isInterrupted()) {
            this.readFullByteArray(imageBuff);
            mBufferManager.fillBuffer(imageBuff, imageBuff.length);
        }
    }
 
    public void readObject1(BitmapListener cameraDataListener) throws Exception {
        setBitmapListener(cameraDataListener);
        while (!Thread.currentThread().isInterrupted()) {
            this.readFullByteArray(imageBuff);
            mBufferManager.fillBuffer(imageBuff, imageBuff.length);
        }
    }
 
    public Object readObject() throws Exception {
        if (useJson) {
            return readJsonAsMap();
        } else {
            return readJsonAsMap();
//            if (objectInputStream == null) {
//                objectInputStream = new ObjectInputStream(inputStream);
//            }
//            return objectInputStream.readObject();
        }
    }
 
    public boolean remoteIpAllowed() {
        return OfficeDeviceManager.remoteIpAllowed(deviceId);
    }
 
    public boolean remoteIpAllowed(Map<String, String> map) {
        if (remoteIpAllowed()) {
            map.put(Constants.SUCCESS, Constants.TRUE);
        } else {
            map.put(Constants.SUCCESS, Constants.FALSE);
        }
        return OfficeDeviceManager.remoteIpAllowed(deviceId);
    }
 
    public boolean writeBitmapHeader() throws Exception {
        boolean success;
        Map<String, String> map = new HashMap<>();
        if (remoteIpAllowed()) {
            map.put(Constants.SUCCESS, Constants.TRUE);
            map.put("type", "data");
            map.put("length", "460800");
            map.put("width", "640");
            map.put("height", "480");
//            map.put("rotation", (Constants.isHuaWeiPad ? 270 : 90) + "");
            map.put("rotation", "270");
            success = true;
        } else {
            map.put(Constants.SUCCESS, Constants.FALSE);
            success = false;
        }
        if (useJson) {
            writeMessage(map);
        } else {
            writeObject(map);
        }
        return success;
    }
 
    public void readOneBitmap() throws Exception {
        if (useJson) {
            readFullByteArray(imageBuff);
            mBufferManager.fillBuffer(imageBuff, imageBuff.length);
        } else {
            byte[] frameData = (byte[]) this.readObject();
            mBufferManager.fillBuffer(frameData, frameData.length);
        }
    }
 
    public boolean writeMap(String key, String value) throws Exception {
        boolean success = false;
        Map<String, Object> map = new HashMap<>();
        if (remoteIpAllowed()) {
            if (key != null && value != null) {
                map.put(key, value);
            }
            map.put(Constants.SUCCESS, Constants.TRUE);
            success = true;
        } else {
            map.put(Constants.SUCCESS, Constants.FALSE);
            success = false;
        }
        writeObject(map);
        return success;
    }
 
    public void writeMap(Map<String, String> map) throws Exception {
        if (useJson) {
            writeMessage(map);
        } else {
            writeObject(map);
        }
    }
 
    public Map<String, Object> readMap() throws Exception {
        return (Map<String, Object>) readObject();
    }
 
    public Object readMapValueByKey(String key) throws Exception {
        return ((Map<String, Object>) readObject()).get(key);
    }
 
    public String readMapStringValueByKey(String key) throws Exception {
        if (useJson) {
            return readJsonAsMap().get(key);
        } else {
            return (String) ((Map<String, Object>) readObject()).get(key);
        }
    }
 
    public Object getBitmapHeader() {
        Map<String, String> map = new HashMap<>();
        map.put(Constants.SUCCESS, Constants.TRUE);
        map.put("type", "data");
        map.put("length", "460800");
        map.put("width", "640");
        map.put("height", "480");
        map.put("rotation", (Constants.isHuaWeiPad ? 270 : 90) + "");
        return map;
    }
 
}