这段代码给了我一些问题。这只是服务的线程部分,用于接收通过TCP连接发送的数据。该数据是通过回调传递给活动的图像(160x120x16bpp = 38400字节)。
public void run() {
Inetaddress serverAddr;
link_respawn = 0;
try {
serverAddr = Inetaddress.getByName(VIDEO_SERVER_ADDR);
} catch (UnknownHostException e) {
Log.e(getclass().getName(),e.getMessage());
e.printStackTrace();
return;
}
Socket socket = null;
DataInputStream stream;
do {
bad_frames = 0;
frames = 0;
status = FrameDecodingStatus.Idle;
try {
socket = new Socket(serverAddr,VIDEO_SERVER_PORT);
stream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
final byte[] _data = new byte[PACKET_SIZE];
final byte[] _image_data = new byte[IMAGE_SIZE];
int _data_index = 0;
while (keepRunning) {
if (stream.read(_data,_data.length) == 0)
continue;
for (byte _byte : _data) {
if (status == FrameDecodingStatus.Idle) {
if (_byte == SoF) {
status = FrameDecodingStatus.Data;
_data_index = 0;
}
} else if ((status == FrameDecodingStatus.Data) && (_data_index < IMAGE_SIZE)) {
_image_data[_data_index] = _byte;
_data_index++;
} else if ((status == FrameDecodingStatus.Data) && (_data_index == IMAGE_SIZE)) {
if (_byte == EoF) {
if(frameReadyCallBack!=null)
frameReadyCallBack.frameReady(_image_data);
frames++;
status = FrameDecodingStatus.Idle;
}
}
}
}
link_respawn++;
Thread.sleep(VIDEO_SERVER_RESPAWN);
Log.d(getclass().getName(),"Link respawn: " + link_respawn);
} catch (Throwable e) {
Log.e(getclass().getName(),e.getMessage());
e.printStackTrace();
}
} while (keepRunning);
if (socket != null) {
try {
socket.close();
} catch (Throwable e) {
Log.e(getclass().getName(),e.getMessage());
e.printStackTrace();
}
}
}
Android activity
以非常奇怪的方式接收回调损坏的数组中的数据。即从某个索引数据开始进入数组设置为0。
如何避免这种情况?