diff options
author | zelig <viktor.tron@gmail.com> | 2014-10-23 23:57:54 +0800 |
---|---|---|
committer | zelig <viktor.tron@gmail.com> | 2014-10-23 23:57:54 +0800 |
commit | 771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb (patch) | |
tree | 15a966dbe15e2f8388f69b396e613c7759b06f6d /p2p/peer.go | |
parent | 119c5b40a7ed1aea1c871c0cb56956b8ef9303d9 (diff) | |
download | dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.tar dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.tar.gz dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.tar.bz2 dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.tar.lz dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.tar.xz dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.tar.zst dexon-771fbcc02e6d10cdf4cda2e8ec8ea23f11066feb.zip |
initial commit of p2p package
Diffstat (limited to 'p2p/peer.go')
-rw-r--r-- | p2p/peer.go | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/p2p/peer.go b/p2p/peer.go new file mode 100644 index 000000000..f4b68a007 --- /dev/null +++ b/p2p/peer.go @@ -0,0 +1,83 @@ +package p2p + +import ( + "fmt" + "net" + "strconv" +) + +type Peer struct { + // quit chan chan bool + Inbound bool // inbound (via listener) or outbound (via dialout) + Address net.Addr + Host []byte + Port uint16 + Pubkey []byte + Id string + Caps []string + peerErrorChan chan *PeerError + messenger *Messenger + peerErrorHandler *PeerErrorHandler + server *Server +} + +func (self *Peer) Messenger() *Messenger { + return self.messenger +} + +func (self *Peer) PeerErrorChan() chan *PeerError { + return self.peerErrorChan +} + +func (self *Peer) Server() *Server { + return self.server +} + +func NewPeer(conn net.Conn, address net.Addr, inbound bool, server *Server) *Peer { + peerErrorChan := NewPeerErrorChannel() + host, port, _ := net.SplitHostPort(address.String()) + intport, _ := strconv.Atoi(port) + peer := &Peer{ + Inbound: inbound, + Address: address, + Port: uint16(intport), + Host: net.ParseIP(host), + peerErrorChan: peerErrorChan, + server: server, + } + connection := NewConnection(conn, peerErrorChan) + peer.messenger = NewMessenger(peer, connection, peerErrorChan, server.Handlers()) + peer.peerErrorHandler = NewPeerErrorHandler(address, server.PeerDisconnect(), peerErrorChan, server.Blacklist()) + return peer +} + +func (self *Peer) String() string { + var kind string + if self.Inbound { + kind = "inbound" + } else { + kind = "outbound" + } + return fmt.Sprintf("%v:%v (%s) v%v %v", self.Host, self.Port, kind, self.Id, self.Caps) +} + +func (self *Peer) Write(protocol string, msg *Msg) error { + return self.messenger.Write(protocol, msg) +} + +func (self *Peer) Start() { + self.peerErrorHandler.Start() + self.messenger.Start() +} + +func (self *Peer) Stop() { + self.peerErrorHandler.Stop() + self.messenger.Stop() + // q := make(chan bool) + // self.quit <- q + // <-q +} + +func (p *Peer) Encode() []interface{} { + return []interface{}{p.Host, p.Port, p.Pubkey} +} |