Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby 1.9.3 用ファイル転送プログラム
#!/usr/bin/env ruby
# encoding : utf-8
require 'socket'
require 'thwait'
def file_send
host = ARGV[0]
q = Queue.new
30.times {q.push(:unlock)}
send_file = ->(name) {
q.pop
Thread.new(name) do |fname|
puts "#{fname} を送信中です..."
open(fname, "rb") do |file|
size = File.size(fname)
TCPSocket.open(host, 7413) do |sock|
sock.set_encoding('ASCII-8BIT')
sock.puts "File,#{fname},#{size}"
sock.write(file.read(size))
end
end
puts "#{fname} の送信が完了しました"
q.push(:unlock)
end
}
send_directory = ->(dname) {
handle_dir = ->(st) {
TCPSocket.open(host, 7413) do |sock|
sock.set_encoding('ASCII-8BIT')
sock.puts st
sock.gets.chomp
end
}
Dir.chdir(dname)
handle_dir.("Mkdir,#{dname}")
puts "ディレクトリ #{dname} の処理をしています..."
threads = []
dirs = []
Dir.glob("*").each do |fname|
if File.directory?(fname)
dirs << fname
else
threads << send_file.(fname)
end
end
ThreadsWait.all_waits(*threads)
dirs.each {|dname| send_directory.(dname)}
handle_dir.("Dirup")
Dir.chdir("..")
}
fnames = ARGV[1..-1].map {|fn| File.expand_path(fn)}
raise "No files or directorys." if fnames.empty?
while (fname = fnames.shift)
Dir.chdir(File.dirname(fname))
fname = File.basename(fname)
if File.file?(fname)
send_file.(fname).join
else
send_directory.(fname)
end
end
puts "すべての送信が終了しました。"
end
def receive
print "IPアドレス: "
puts %r(192\.168\.11\.\d+).match(`ip -4 a`)[0]
s = TCPServer.open(7413)
loop do
Thread.new(s.accept) do |sock|
puts "[#{sock.peeraddr[3]}:#{sock.peeraddr[1]}] からの接続を了承しました"
sock.set_encoding('UTF-8')
ar = sock.gets.chomp.split(',')
case ar[0]
when "File"
fname, size = ar.drop(1)
puts "#{fname} を受信中です..."
open("#{fname}", "wb") do |file|
file.write(sock.read(size.to_i))
end
puts "#{fname} の受信が完了しました"
when "Mkdir"
begin
Dir.mkdir(ar[1])
rescue
puts "ディレクトリが作成できません。"
sock.close
exit 1
end
Dir.chdir(ar[1])
puts "ディレクトリ #{ar[1]} を作成しました。"
sock.puts :done
when "Dirup"
Dir.chdir("..")
sock.puts :done
else
raise "error: 予期せぬコマンドです。"
end
sock.close
end
end
end
if ARGV.size.zero?
receive
else
file_send
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.