使用Ruby的TCPSocket-Class发送原始字节数组的最简单方法

flo*_*tto 2 ruby network-programming tcp bytearray tcp-ip

我想使用Rubys TCPSocket-Class发送原始字节.有人举个好榜样吗?

我试过这种方式,但它不起作用:(

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"
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Tim*_*ter 8

尝试在format指令后使用"*"来吃掉列表中的所有元素:

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*')
Run Code Online (Sandbox Code Playgroud)

使用string#格式有很多巧妙的技巧,因此值得研究文档.