如何使用ruby分析从TCP接收二进制流

如何使用ruby分析从TCP接收二进制流,ruby,sockets,Ruby,Sockets,我将要接收设备上的数据,但这些数据是二进制流,我把这些数据存储起来,然后读取以正确显示它们,有更好的方法吗 require 'socket' server = TCPServer.open(2000) loop { Thread.start(server.accept) do |client| File.open("tmp","w") { |file| file.write(client.gets)} File.open("tmp").each do |f| p

我将要接收设备上的数据,但这些数据是二进制流,我把这些数据存储起来,然后读取以正确显示它们,有更好的方法吗

require 'socket'

server = TCPServer.open(2000)
loop {
  Thread.start(server.accept) do |client|

    File.open("tmp","w") { |file| file.write(client.gets)}
    File.open("tmp").each do |f|
     puts f.unpack('H*')
    end

    client.puts(Time.now.ctime) # Send the time to the client
    client.puts "Closing the connection. Bye!"
    client.close                # Disconnect from the client
  end
}
接收到的数据如下:xx^Q^A^Hb0@26 2^B^@ev

我想要这样:787811010862304020903236202032020001c26c0d0a


对不起,我的英语很差!

如果有多个客户端发送数据,则使用带有名称的临时文件将导致问题;临时文件将被覆盖

您不需要使用临时文件

require 'socket'

server = TCPServer.open(2000)
loop {
  Thread.start(server.accept) do |client|
    puts client.gets.unpack('H*')
    client.puts(Time.now.ctime) # Send the time to the client
    client.puts "Closing the connection. Bye!"
    client.close
  end
}