ByteBuffer isn't filled with correct data

recently I switched from multithreaded sockets to NIO sockets.
Unfortunately I’m struggling with converting raw packet data to the ByteBuffer (or something similiar to it)

Well here you have two outputs, one of the resulting packet and the resulting ByteBuffer content that should be sent.

SEND [0xfa2] 00 00 00 00 A2 0F 02 00 FE FF // the packet that should be sent SEND [0xfa2] 00 00 00 00 A2 0F 02 00 00 00 // ByteBuffer content that is sent 

As you can see, the last two bytes in this example are nulled out. And I have no idea why.
The data contains a char object (-2). (data.write((char) -2));)

Here is the code on how I wrap up the data into the ByteBuffer:

public int send(Connection connection, Packet packet) throws IOException {      SocketChannel socketChannel = this.socketChannel;     if(socketChannel == null)         throw new SocketException("Connection is closed.");      synchronized (writeLock) {          writeBuffer = ByteBuffer.allocate(packet.getDataLength() + 8);         writeBuffer.order(ByteOrder.LITTLE_ENDIAN);                  // checksum         writeBuffer.putInt(0);         // packet         writeBuffer.putChar(packet.getPacketId());         writeBuffer.putChar(packet.getDataLength());         writeBuffer.put(packet.getData(), 8, packet.getDataLength());          // print content of Packet         System.out.println("SEND [" + String.format("0x%x", (int)packet.getPacketId()) + "] " + BitKit.toString(packet.getRawPacket(), 0, packet.getDataLength() + 8));         // print content of ByteBuffer         System.out.println("SEND [" + String.format("0x%x", (int)packet.getPacketId()) + "] " + BitKit.toString(writeBuffer.array(), 0, writeBuffer.array().length));                  if(!writeToSocket()) {              selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);         } else {             selectionKey.selector().wakeup();         }          lastWriteTime = System.currentTimeMillis();          return packet.getDataLength();     } } 

The method writeToSocket() just writes the buffer.

private boolean writeToSocket() throws IOException {      SocketChannel socketChannel = this.socketChannel;     if(socketChannel == null)         throw new SocketException("Connection is closed.");      ByteBuffer buffer = writeBuffer;     buffer.flip();     while(buffer.hasRemaining()) {          if(socketChannel.write(buffer) == 0)             break;     }     buffer.compact();      return buffer.position() == 0; } 

I hope you can help me out! Thanks in advance!

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.