简体   繁体   English

java nio和ByteBuffer问题

[英]java nio and ByteBuffer problem

I met a problem.我遇到了一个问题。 I use nio socket to receive message.我使用 nio socket 来接收消息。 Upon a complete message is received, I send the dataBuffer which holds the received message to another user.收到完整消息后,我将保存收到消息的 dataBuffer 发送给另一个用户。 But there is exception below.但下面有例外。 Where is the problem?问题出在哪里? I try to call dataBuffer.duplicate() and write it out.我尝试调用 dataBuffer.duplicate() 并将其写出来。 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.我必须分配一个新的 ByteBuffer 并制作一个新的消息副本并将其写出来。 In this case, there is no error.在这种情况下,没有错误。 But I do not want the copy step.但我不想要复制步骤。 Is there any other way to solve it?有没有其他方法可以解决它?

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);

}

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.每当您将数据读入缓冲区时,如果要将缓冲区写入另一个通道,则需要在写入之前调用: buffer.flip() You don't need to duplicate the buffer if you are writing on the same thread as you are reading.如果您在阅读时在同一个线程上写入,则不需要复制缓冲区。

Also - BufferOverflowException means you are putting more data into the buffer than its capacity.此外 - BufferOverflowException 意味着您将更多的数据放入缓冲区而不是其容量。 This sounds like a buffer is not getting buffer.clear() called to reset the position to zero.这听起来像一个缓冲区没有调用buffer.clear()来将 position 重置为零。

There isn't enough code written above to diagnose exactly what the problem is.上面没有足够的代码来准确诊断问题所在。

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 .java 文档中阅读有关清除、倒带和翻转的信息。 This will reset position, limit or size of buffer.这将重置 position、缓冲区的限制或大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM