这段代码给我带来了一些问题。这只是服务的线程部分,用于接收通过 TCP 连接发送的数据。此数据是通过回调提供给 Activity 的图像(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, 0, _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; } } } }接收回调的Android发现数组中的数据以一种非常奇怪的方式损坏..即从某个索引开始数组中的数据被 设置为0。我怎样才能避免这种情况?Activity
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
read不是readFully。三参数read返回已读取的字节数,这不一定是所提供数组的完整长度。
此代码删除read返回值并处理整个数组。
if (stream.read(_data, 0, _data.length) == 0)
continue;
for (byte _byte : _data) {
添加回答
举报
0/150
提交
取消