Joel VanderWerf wrote:
> Javier None wrote:
> ...
>> data = 10
>> socket = TCPSocket.new(home,port)
>> socket.write(data)
>> 
>> on the other end I get
>> receieved byte dump
>> 0000: 31 30                10
>> 
>> which is the ascii for 10. How can I tell Ruby to send the 0x10?
> 
> IIRC, #write(arg) is converting arg to a string, so the number 10 is
> converted to the string "10", as you noticed.
> 
> If you construct the string yourself, you can control what binary data
> is in this string:
> 
> irb(main):029:0> data = "\012"
> => "\n"
> irb(main):030:0> data[0]
> => 10
> 
> (note that \nnn uses octal).
> 
> But since it's hard to handle endianness and multibyte numbers this way,
> you probably want to use pack/unpack as Axel suggested.
> 
> If you want a friendly interface to do this, check out my bit-struct 
> lib:
> 
> http://redshift.sourceforge.net/bit-struct/
> 
> For example:
> 
> ---------------------------------
> require 'bit-struct'
> 
> class MyData < BitStruct    # typedef struct{
>    unsigned  :type,  32      #   u_int32_t type;
>    unsigned  :len,   8       #   u_int8_t len;
>    rest      :buf            #   u_int8_t * buf;
> end                         # }
> 
> data = MyData.new
> data.type = 1234
> data.buf = "fred flintstone"
> data.len = data.buf.length
> 
> p data       # ==> #<MyData type=1234, len=15, buf="fred flintstone">
> p data.to_s  # ==> "\000\000\004\322\017fred flintstone"
> ---------------------------------
> 
> Note that the number format is big-endian (by default), which makes
> sense if you're writing network code.
> 
> Also note that the pointer is replaced with the buf bytes themselves,
> which is probably how you want it (you didn't really want to send a
> pointer over a tcp socket, right?).

just installed it! works.

client....
class Tdata < BitStruct
  unsigned :type,  32
  rest     :buf
end

data = Tdata.new
data.type = 987 #03DB
data.buf = "push to talk"

socket = TCPSocket.new(home,port)

server writes.....
0000: 00 00 03 DB 70 75 73 68 20 74 6F 20 74 61 6C 6B   ....push to talk

we get big endian, that can be managed on the server side with 
htonl,htons.
Thanks!

-- 
Posted via http://www.ruby-forum.com/.