tyrus
tyrus copied to clipboard
Issues with binary decoder message Decoder.Binary<T>
Hi, i am having trouble with the receiving end of the transfer of binary messages. My encoder looks like this:
public class MessageEncoder implements Encoder.Binary<Message> {
@Override
public ByteBuffer encode(Message message) throws EncodeException {
System.out.println("Encoding "+message.getMsg().length);
byte[] toSend = message.getMsg();
ByteBuffer buff = ByteBuffer.allocate(toSend.length);
buff.put(toSend);
return buff;
}
@Override
public void init(EndpointConfig endpointConfig) {
}
@Override
public void destroy() {
}
}
While my Decoder looks like this
public class MessageDecoder implements Decoder.Binary<Message>{
@Override
public Message decode(ByteBuffer byteBuffer) throws DecodeException {
byte[] arr = byteBuffer.array();
System.out.println("Length "+arr.length);
return new Message(arr);
}
@Override
public boolean willDecode(ByteBuffer byteBuffer) {
return byteBuffer != null;
}
@Override
public void init(EndpointConfig endpointConfig) {
}
@Override
public void destroy() {
}
}
The output of the encoder is always 'Encoding X' where X is the actual number of bytes that are encoded. While in the Decoder the output is always 'Length 0' meaning the ByteBuffer parameter was empty on arrival. Is this a known bug or am i doing something wrong ?
I guess you have to flip the ByteBuffer in your MessageEncoder before returning it: https://docs.oracle.com/javase/8/docs/api/java/nio/Buffer.html#flip--
Alternatively you could use ByteBuffer.wrap(message.getMsg()) and return the resulting ByteBuffer instance.