回调中的 Java 数组数据损坏

这段代码给我带来了一些问题。这只是服务的线程部分,用于接收通过 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


森栏
浏览 26回答 1
1回答

呼啦一阵风

read不是readFully。三参数read返回已读取的字节数,这不一定是所提供数组的完整长度。此代码删除read返回值并处理整个数组。&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (stream.read(_data, 0, _data.length) == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (byte _byte : _data) {
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java