class Bitcourier::Node
Attributes
context[RW]
remote_port[RW]
socket[RW]
state[RW]
Public Class Methods
new(context, socket)
click to toggle source
# File lib/bitcourier/node.rb, line 81 def initialize(context, socket) self.socket = socket self.context = context end
Public Instance Methods
disconnect()
click to toggle source
# File lib/bitcourier/node.rb, line 92 def disconnect socket.close end
on_message(msg)
click to toggle source
# File lib/bitcourier/node.rb, line 129 def on_message msg return if state.nil? case msg when Protocol::Message::Hello state.on_hello(msg) when Protocol::Message::GetPeerList state.on_get_peer_list(msg) when Protocol::Message::PeerInfo state.on_peer_info(msg) else puts "Don't know how to handle message class #{msg.class}" end end
on_peer_info(msg)
click to toggle source
# File lib/bitcourier/node.rb, line 125 def on_peer_info msg context.peer_list.store Peer.new(msg.ip, msg.port, msg.last_seen_at) end
remember_peer()
click to toggle source
# File lib/bitcourier/node.rb, line 96 def remember_peer remote_ip = socket.peeraddr[3] peer = Peer.new remote_ip, remote_port context.peer_list.store peer end
run()
click to toggle source
# File lib/bitcourier/node.rb, line 144 def run @thread = Thread.new do buffer = '' begin loop do data = socket.recv(1024) break if data.length == 0 buffer += data while (message_size = Protocol::Message::Base.message_size(buffer)) > 0 message_data = buffer.slice!(0, message_size) message = Protocol::Message::Base.unpack(message_data) on_message message end end rescue IOError puts "Connection closed" end end end
send_hello()
click to toggle source
# File lib/bitcourier/node.rb, line 103 def send_hello msg = Protocol::Message::Hello.new msg.port = context.server.port msg.nonce = context.nonce send_message msg end
send_message(msg)
click to toggle source
# File lib/bitcourier/node.rb, line 120 def send_message msg data = msg.pack socket.write data end
send_peer_list()
click to toggle source
# File lib/bitcourier/node.rb, line 110 def send_peer_list context.peer_list.peers.each do |peer| msg = Protocol::Message::PeerInfo.new msg.ip = peer.ip msg.port = peer.port msg.last_seen_at = peer.last_seen_at send_message msg end end
set_state(state)
click to toggle source
# File lib/bitcourier/node.rb, line 86 def set_state state self.state.on_leave if self.state self.state = state.new(self) self.state.on_enter end