Ruby Socket文件传输更改文件md5

时间:2018-01-08 05:03:03

标签: ruby md5

我尝试使用套接字传输文件,但我发现Ruby套接字传输文件将更改文件的MD5。那么,我能为此做些什么呢?

这是我的代码:

server.rb

require 'socket'
server = TCPServer.open(13302)
BLOCK_SIZE = 1024
while true

  file = File.open('./test_file.zip', 'rb')
  data_len = file.size
  puts 'file size : ' + data_len.to_s + ' byte'


  client = server.accept
  puts 'client connected'
  client.puts data_len

  if data_len < BLOCK_SIZE
    client.puts file.read(data_len)
  else
    transfer_times = data_len / BLOCK_SIZE
    remain_data_size = data_len % BLOCK_SIZE
    written_size = 0

    i = 0
    while i < transfer_times
      client.puts file.read(BLOCK_SIZE)
      i += 1
      written_size += BLOCK_SIZE
    end

    puts 'remain_size : ' + remain_data_size.to_s
    client.puts file.read(remain_data_size)
    written_size += remain_data_size

    puts 'written_size : ' + written_size.to_s
  end
  client.close
  puts 'client disconnected'
end

client.rb

require 'socket'
host = 'localhost'
port = 13302
file_name = './new_copy_file.zip'
BLOCK_SIZE = 1024
begin
  server = TCPSocket.open(host, port)
  File.delete(file_name) if File.exist?(file_name)
  file = File.open(file_name, 'wb')
  file_size = server.readline.to_i 
  transfer_times = file_size / BLOCK_SIZE
  remain_data_size = file_size % BLOCK_SIZE
  read_size = 0.0

  times = 0
  while times < transfer_times
    line = server.read(BLOCK_SIZE)
    read_size += line.size
    file.write(line)
    times += 1
    puts 'downloaded : ' + ((read_size / file_size) * 100).to_s + '%'
  end

  file.write server.read(remain_data_size)
  read_size += remain_data_size

  puts 'file size : ' + file_size.to_s + ' byte'
  puts 'receive size : ' + read_size.to_s + ' byte'
  file.close
rescue => e
  puts 'connect failed : ' + e.message
end

传输的文件将正确打开,但使用不同的MD5。

如何在通讯期间确保文件具有相同的MD5? 谢谢!

1 个答案:

答案 0 :(得分:2)

错误是server.rb中的这三行:

  • client.puts file.read(data_len)
  • client.puts file.read(BLOCK_SIZE)
  • client.puts file.read(remain_data_size)

您应该使用client.write代替client.putsputs添加换行符。