I have an application that show CCTV feed from mobile. I successfully develop iOS application and now my client wants me to port to Android. The porting was fine until I'm stuck at this part of code.
This part of code, I have to connect to TCP socket server. When connected, I don't have to send server any thing, instead, server will send me a JPEG image. So, after connected, I'll have to keep reading until I received JPEG end marker (0xFF, 0xD9) and then close the connection.
What I plan to do is
Socket s = new Socket("Server IP Addreess", SERVER_PORT);
DataInputStream dis = new DataInputStream(socket.getInputStream());
ArrayList<Byte> bytes = new ArrayList<Byte>();
boolean err = false;
while (true) {
byte b = dis.readByte();
if (b == -1) {
err = true;
break;
}
bytes.add(b);
if ((bytes.get(bytes.size() - 1) == (byte) 0xFF) &&
(bytes.get(bytes.size() - 2) == (byte) 0xD9)) {
break;
}
}
socket.close();
if (!err) {
// create bitmap from byte array and show in ImageView
}
But I'm not sure that this is correct or not. The other solution I'm thinking about is
Socket s = new Socket("Server IP Addreess", SERVER_PORT);
BitmapFactory.decodeStream(s.getInputSteam());
But, also, I don't know how to close socket when server send 0xFF, 0xD9. Or will the BitmapFactory will detect that marker and close socket connection for me?
Any suggestion are welcome. Thank you!
PS I don't have test environment as they took it back when I delivered iOS app. So, I have to develop and then deliver to them to test (by playing with the app). Then if it's not working, they will tell me to correct it but I won't be able to access LogCat or other useful information. This is just like trying to sew a button in dark room, and I can't turn on the light.
: |
EDIT
More information about this server
Also, I'm getting one image for each TCP connection , I'm not getting multiple images for single TCP connection.
This is a bad idea to just look for some magic bytes to determine the end of the data. While these magic bytes should be at the end of the file they can also happen inside the data.
Better would be to either prefix the data with the length or use a separate TCP connection for each jpeg file and just read until the end of connection (that is until you don't get any more data). If this is not possible you have to do more advanced parsing, see Detect Eof for JPG images .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.