3

i want to send raw bytes using Rubys TCPSocket-Class. Has someone a good example?

I've tried it in this way, but it does not work :(

require 'socket'

host = '192.168.0.80'
port = 102
s = TCPSocket.new(host, port)

    s.write [0x03, 0x00, 0x00, 0x16,
             0x11, 0xE0, 0x00, 0x00, 0x00, 
             0x01, 0x00, 0xC1, 0x02, 0x02, 
             0x02, 0xC2, 0x02, 0x02, 0x02, 
             0xC0, 0x01, 0x0A ].pack('C')
    puts s.read
    s.close

puts "exit"

thanks :)

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
flotto
  • 535
  • 5
  • 17
  • first: its s.write instead of s.send, sorry... i don't know what exactly is going wrong, but it seems so that the write-method converts my byte-array into a string. – flotto Feb 17 '12 at 10:22
  • 1
    I edited the post for you, but in future please correct it yourself. – Sergio Tulentsev Feb 17 '12 at 10:24

1 Answers1

9

Try using a "*" after the format directive to eat all the elements in the list:

s.write [0x03, 0x00, 0x00, 0x16,
         0x11, 0xE0, 0x00, 0x00, 0x00, 
         0x01, 0x00, 0xC1, 0x02, 0x02, 
         0x02, 0xC2, 0x02, 0x02, 0x02, 
         0xC0, 0x01, 0x0A ].pack('C*')

There are lots of neat tricks possible with string#format so it's worth studying the documentation.

Tim Potter
  • 2,437
  • 21
  • 31