首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java -从socketchannel读取

Java -从socketchannel读取
EN

Stack Overflow用户
提问于 2016-12-15 18:24:37
回答 1查看 1K关注 0票数 1

所以我在java中使用SocketChannels来发送和接收项目的数据。该项目与第三方进行交互,该第三方需要数据的ByteBuffer,但其前缀为4字节,这是其长度。

在接收时,我将收到一个ByteBuffer,我需要它从前面解构4个字节的长度并提取数据。我收到的消息不是固定长度的。

我目前的实现如下:

代码语言:javascript
复制
public PedResponse send(ByteBuffer message) {
        String returnString;
        try {

            message.flip();

            while (message.hasRemaining()) {
                socketChannel.write(message);
            }

            ByteBuffer readBuffer = ByteBuffer.allocate(5000);
            int bufferSize = socketChannel.read(readBuffer);
            if (bufferSize == -1) {
                socketChannel.close();
            } else {
                readBuffer.flip();
            }

            returnString = new String(deconstructMessage(readBuffer.array()), "UTF-8").trim();

            response = parser.parseResponse(returnString);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

private ByteBuffer constructMessage(byte[] data) {

        // Construct a buffer where we'll put the data to send
        ByteBuffer sendBuffer = ByteBuffer.allocate(4 + data.length);

        // it's the default, but included for clarity
        sendBuffer.order(ByteOrder.BIG_ENDIAN);

        // Put the 4-byte length, then the data
        sendBuffer.putInt(data.length);
        sendBuffer.put(data);

        // Extract the actual bytes from our sendBuffer
        return sendBuffer;
    } 

public byte[] deconstructMessage(byte[] data) {

        byte[] filteredByteArray = Arrays.copyOfRange(data, 4, data.length - 4);

        return filteredByteArray;
    }

//Currently not being used.
private byte[] deconstructMessage(byte[] data) {

        // Construct a buffer where we'll put the data to send
        ByteBuffer receiveBuffer = ByteBuffer.allocate(data.length);

        // it's the default, but included for clarity
        receiveBuffer.order(ByteOrder.BIG_ENDIAN);

        // Get the 4-byte length, then the data
        receiveBuffer.getInt(data.length);
        receiveBuffer.get(data);

        // Extract the actual bytes from our receivedBuffer
        byte[] dataReceived = receiveBuffer.array();
        return dataReceived;
    }

正如您所看到的,我正在创建一个大小为5000的新ByteBuffer,但理想情况下我不想这样做。所以我的问题是,我如何才能不使用这个超大的ByteBuffer,而是只读取我收到的数据,这样我就可以使用我未使用的解构消息方法?

EN

回答 1

Stack Overflow用户

发布于 2016-12-15 19:12:20

ByteBuffer有method get(),它从当前位置返回字节。所以,你可以先读取4个字节,然后得到大小。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41161813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档