java nio 和 ByteBuffer 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6206336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java nio and ByteBuffer problem
提问by susan
I met a problem. I use nio socket to receive message. Upon a complete message is received, I send the dataBuffer which holds the received message to another user. But there is exception below. Where is the problem? I try to call dataBuffer.duplicate() and write it out. But at the receiver side, the read operation throws such exception. I have to assign a new ByteBuffer and make a new copy of message and write it out. In this case, there is no error. But I do not want the copy step. Is there any other way to solve it?
我遇到了一个问题。我使用 nio 套接字接收消息。收到完整的消息后,我将保存接收到的消息的 dataBuffer 发送给另一个用户。但下面有例外。哪里有问题?我尝试调用 dataBuffer.duplicate() 并将其写出。但是在接收端,读操作抛出了这样的异常。我必须分配一个新的 ByteBuffer 并制作一个新的消息副本并将其写出。在这种情况下,没有错误。但我不想要复制步骤。有没有其他方法可以解决?
Exception thrown
抛出异常
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(Unknown Source)
at java.nio.ByteBuffer.put(Unknown Source)
at serviceHandlerPackage.ServiceHandler.readComplete(ServiceHandler.java:218)
Code
代码
readEventHAndler(SocketChannel socket) {
readCompleteData(socket);
}
readCompleteData(Socket) {
ByteBuffer dataBuffer; //hold complete message
if(!dataComplete) return;
else process(dataBuffer);
}
process(dataBuffer) {
...
processHandler();
sendNext(dataBuffer);
}
sendNext(dataBuffer) {
write(dataBuffer);
}
回答by Sam Goldberg
Whenever you read data into a buffer, if you want to write the buffer out another channel, you need to call: buffer.flip()
before writing. You don't need to duplicate the buffer if you are writing on the same thread as you are reading.
每当您将数据读入缓冲区时,如果要将缓冲区写出另一个通道,则需要buffer.flip()
在写入之前调用: 。如果您在阅读时在同一线程上写入,则不需要复制缓冲区。
Also - BufferOverflowException means you are putting more data into the buffer than its capacity. This sounds like a buffer is not getting buffer.clear()
called to reset the position to zero.
此外 - BufferOverflowException 意味着您将更多的数据放入缓冲区而不是其容量。这听起来像是没有buffer.clear()
调用缓冲区来将位置重置为零。
There isn't enough code written above to diagnose exactly what the problem is.
上面编写的代码不足以准确诊断问题所在。
回答by teodozjan
Your program throws an exception while putting data so I would say that something is wrong with position/limit.
您的程序在放置数据时抛出异常,所以我会说位置/限制有问题。
It looks like you are trying to put data into read buffer or trying to put more data than it's size. Buffer will not grow itself (ByteArrayOutputStream is better for this).
看起来您正在尝试将数据放入读取缓冲区或尝试放入超过其大小的数据。缓冲区不会自行增长(ByteArrayOutputStream 对此更好)。
Read about clearing, rewinding and flipping in java documentation. This will reset position, limit or size of buffer.