2

I need to create a Bytebuffer like object in Ruby. Here is my example in JAVA

int ADD_BYTES_FOR_MSG_LENGTH = 4;

Integer messageBodySize = new Integer(messageBody.getBytes().length);
byte[] messageHeader = ByteBuffer.allocate(ADD_BYTES_FOR_MSG_LENGTH).putInt(messageBodySize).array();

messageToSend = new byte[messageHeader.length + messageBodySize];

System.arraycopy(messageHeader, 0, messageToSend, 0, messageHeader.length);
System.arraycopy(messageBody.getBytes(), 0, messageToSend, messageHeader.length, messageBodySize);

I create a message starting with 4 bytes where is located size of the message body part, and then the actual message. I have no idea how to do this in Ruby, so please help.

1 Answer 1

4

I did this for Steam Condenser using an extended version of StringIO.

Although I don't use any put* methods, these could be easily implemented like for example:

class StringIO

  def put_int(i)
    write [i].pack('v')
  end

end

You may have a look at the code, the documentation of the original class and my extensions.

Sign up to request clarification or add additional context in comments.

6 Comments

I guess you should use write instead of puts there?
Thanks for help, but now I'm stuck again... when I do write [i].pack('L') (unsigned 32 bit integer) the StringIO object is allocating 5 bytes (method size is returning 5). I need to write this int on 4 bytes only (like in my java example). Could you give me a hint how to handle it?
@Neuro: Are you using write or puts? puts will append a newline and give you an extra byte, write won't. There's also syswrite which might match your desired semantics better.
Yes! Stupid me. Classic copy-paste error. But unfortunately something is not working :/ I do put_int(size_of_msg) and then write(msg) on the StringIO object and I send it through the socket but in java side app I don't get expected message :/
I got it! I did it by write [i].pack('N') for unpack in network byte order :) And i wrote to the socket by stringioobj.string method. Many thanks for all of you for help, this problem was pain in my ass for almost a week :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.