Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a ruby bit-struct to a socket

Tags:

ruby

sockets

I've written a bit-struct in Ruby:

class UnitHeader < BitStruct
    default_options :endian => :little
    unsigned :len,          16,  "Length including header and all payload messages"
    unsigned :msgCount,     8,   "Number of messages in payload"
    unsigned :group,        8,   "group the payload messages relate to"
    unsigned :seqNumStart,  32,  "Sequence number of the first payload message"
end

I'd like to write this to a socket:

uh = UnitHeader.new
...

s = TCPSocket.new("127.0.0.1", 3000)
s.write(uh)

The s.write call doesn't seem to write any data. I've been unable to find anything on this issue in the documentation, is there a ruby operator or similar for this purpose?

like image 537
user3419593 Avatar asked Jul 31 '26 06:07

user3419593


1 Answers

The code you've presented should work properly. Your problem is probably located elsewhere. Here's how you can debug it to be sure:

  1. Create a UnitHeader and set the appropriate values.
  2. Using netcat, create a listener socket to test with, and dump the received data to a file: nc -l 1234 > output, where 1234 is the port to listen on.
  3. Run your code (be sure to flush or close your socket)
  4. Use hexdump output to look at the result, and compare it to your expected result
like image 170
fresskoma Avatar answered Aug 02 '26 23:08

fresskoma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!