gpt4 book ai didi

Java - 从套接字 channel 读取

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:20 25 4
gpt4 key购买 nike

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

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

我当前的实现如下:

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,而只是读取我收到的数据,这样我就可以使用我未使用的解构消息方法?

最佳答案

ByteBuffer有method get()它从当前位置返回字节。因此,您可以先读取 4 个字节并获取大小。

关于Java - 从套接字 channel 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41161813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com