本文介绍了使用Ruby的TCPSocket-Class发送原始字节数组的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

感谢:)

推荐答案

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

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*')

string#format有许多巧妙的技巧,因此值得研究.

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

这篇关于使用Ruby的TCPSocket-Class发送原始字节数组的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 18:13