You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.5 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. package p2p
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "sync/atomic"
  7. . "github.com/tendermint/tendermint/binary"
  8. )
  9. /* Peer */
  10. type Peer struct {
  11. outbound bool
  12. mconn *MConnection
  13. started uint32
  14. stopped uint32
  15. }
  16. func newPeer(conn net.Conn, outbound bool, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer {
  17. var p *Peer
  18. onError := func(r interface{}) {
  19. p.stop()
  20. onPeerError(p, r)
  21. }
  22. mconn := NewMConnection(conn, chDescs, onError)
  23. p = &Peer{
  24. outbound: outbound,
  25. mconn: mconn,
  26. stopped: 0,
  27. }
  28. mconn._peer = p // hacky optimization
  29. return p
  30. }
  31. func (p *Peer) start() {
  32. if atomic.CompareAndSwapUint32(&p.started, 0, 1) {
  33. log.Debug("Starting %v", p)
  34. p.mconn.Start()
  35. }
  36. }
  37. func (p *Peer) stop() {
  38. if atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
  39. log.Debug("Stopping %v", p)
  40. p.mconn.Stop()
  41. }
  42. }
  43. func (p *Peer) IsOutbound() bool {
  44. return p.outbound
  45. }
  46. func (p *Peer) RemoteAddress() *NetAddress {
  47. return p.mconn.RemoteAddress()
  48. }
  49. func (p *Peer) TrySend(chId byte, bytes ByteSlice) bool {
  50. if atomic.LoadUint32(&p.stopped) == 1 {
  51. return false
  52. }
  53. return p.mconn.TrySend(chId, bytes)
  54. }
  55. func (p *Peer) Send(chId byte, bytes ByteSlice) bool {
  56. if atomic.LoadUint32(&p.stopped) == 1 {
  57. return false
  58. }
  59. return p.mconn.Send(chId, bytes)
  60. }
  61. func (p *Peer) WriteTo(w io.Writer) (n int64, err error) {
  62. return p.RemoteAddress().WriteTo(w)
  63. }
  64. func (p *Peer) String() string {
  65. if p.outbound {
  66. return fmt.Sprintf("P(->%v)", p.mconn)
  67. } else {
  68. return fmt.Sprintf("P(%v->)", p.mconn)
  69. }
  70. }