simplest way to send raw Byte-arrays using Ruby's TCPSocket-Class

百般思念 提交于 2019-12-29 06:33:06

问题


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 :)


回答1:


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.



来源:https://stackoverflow.com/questions/9326424/simplest-way-to-send-raw-byte-arrays-using-rubys-tcpsocket-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!