tendermint/p2p/peer.go

84 lines
1.5 KiB
Go
Raw Normal View History

2014-07-07 20:03:50 -07:00
package p2p
2014-06-18 20:48:32 -07:00
import (
2014-07-01 14:50:24 -07:00
"fmt"
"io"
"net"
2014-07-01 14:50:24 -07:00
"sync/atomic"
. "github.com/tendermint/tendermint/binary"
2014-06-18 20:48:32 -07:00
)
2014-06-24 17:28:40 -07:00
/* Peer */
2014-06-18 20:48:32 -07:00
2014-06-24 17:28:40 -07:00
type Peer struct {
2014-07-10 22:14:23 -07:00
outbound bool
mconn *MConnection
started uint32
stopped uint32
2014-06-18 20:48:32 -07:00
}
func newPeer(conn net.Conn, outbound bool, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer {
var p *Peer
onError := func(r interface{}) {
p.stop()
onPeerError(p, r)
}
mconn := NewMConnection(conn, chDescs, onError)
p = &Peer{
outbound: outbound,
mconn: mconn,
stopped: 0,
2014-07-01 14:50:24 -07:00
}
mconn._peer = p // hacky optimization
return p
2014-06-28 13:09:04 -07:00
}
func (p *Peer) start() {
if atomic.CompareAndSwapUint32(&p.started, 0, 1) {
log.Debug("Starting %v", p)
p.mconn.Start()
2014-07-01 14:50:24 -07:00
}
2014-06-18 20:48:32 -07:00
}
func (p *Peer) stop() {
2014-07-01 14:50:24 -07:00
if atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
2014-07-14 16:15:13 -07:00
log.Debug("Stopping %v", p)
p.mconn.Stop()
2014-07-01 14:50:24 -07:00
}
2014-06-18 20:48:32 -07:00
}
2014-07-10 22:14:23 -07:00
func (p *Peer) IsOutbound() bool {
return p.outbound
2014-07-09 18:33:44 -07:00
}
2014-06-24 17:28:40 -07:00
func (p *Peer) RemoteAddress() *NetAddress {
return p.mconn.RemoteAddress()
2014-06-18 20:48:32 -07:00
}
func (p *Peer) TrySend(chId byte, bytes ByteSlice) bool {
if atomic.LoadUint32(&p.stopped) == 1 {
2014-07-01 14:50:24 -07:00
return false
}
return p.mconn.TrySend(chId, bytes)
2014-06-18 20:48:32 -07:00
}
func (p *Peer) Send(chId byte, bytes ByteSlice) bool {
if atomic.LoadUint32(&p.stopped) == 1 {
return false
}
return p.mconn.Send(chId, bytes)
}
2014-06-24 17:28:40 -07:00
func (p *Peer) WriteTo(w io.Writer) (n int64, err error) {
2014-07-01 14:50:24 -07:00
return p.RemoteAddress().WriteTo(w)
2014-06-18 20:48:32 -07:00
}
2014-06-29 00:35:16 -07:00
func (p *Peer) String() string {
2014-07-17 00:54:48 -07:00
if p.outbound {
return fmt.Sprintf("P(->%v)", p.mconn)
2014-07-17 00:54:48 -07:00
} else {
return fmt.Sprintf("P(%v->)", p.mconn)
2014-07-01 14:50:24 -07:00
}
2014-06-18 20:48:32 -07:00
}