Created
April 19, 2009 08:50
-
-
Save qnighy/97977 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!ruby -Ku | |
require "socket" | |
require "yaml" | |
class RP2P | |
def save_stat | |
File.open("stat#@port.yml", "w") do|file| | |
YAML.dump(@stat, file) | |
end | |
end | |
def dialogue(sock) | |
Thread.new do | |
pa = sock.peeraddr | |
sock.puts "connect #@port" | |
while buf = sock.gets | |
buf.chomp! | |
case buf | |
when /^connect (\d+)/ then | |
node = [pa[3], $1.to_i] | |
@nodes[node] = {} unless @nodes.has_key? node | |
save_stat | |
puts "info> connected #{node.inspect}" | |
else | |
p buf | |
end | |
end | |
sock.close | |
end | |
end | |
def open_as_client(node) | |
dialogue(TCPSocket.open(node[0],node[1])) | |
end | |
def initialize(port) | |
@port = port | |
@stat = YAML.load_file("stat#@port.yml") rescue {} | |
@stat ||= {} | |
@nodes = @stat["nodes"] ||= {} | |
end | |
def start | |
puts "current nodes:" | |
print @nodes.keys.join("\n") | |
t = Thread.new do | |
serv = TCPServer.open(@port) | |
loop do | |
sock = serv.accept | |
dialogue(sock) | |
end | |
serv.close | |
end | |
if @port != 18782 then | |
open_as_client(["localhost", 18782]) | |
end | |
$stdin.readline | |
end | |
end | |
Signal.trap(:INT) do | |
exit | |
end | |
port = 18782 | |
port = ARGV[0].to_i if ARGV[0] | |
rp = RP2P.new(port) | |
rp.start | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment