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.

93 lines
1.7 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
  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. Key string
  16. }
  17. func newPeer(conn net.Conn, outbound bool, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer {
  18. var p *Peer
  19. onError := func(r interface{}) {
  20. p.stop()
  21. onPeerError(p, r)
  22. }
  23. mconn := NewMConnection(conn, chDescs, onError)
  24. p = &Peer{
  25. outbound: outbound,
  26. mconn: mconn,
  27. stopped: 0,
  28. Key: mconn.RemoteAddress.String(),
  29. }
  30. mconn.Peer = p // hacky optimization
  31. return p
  32. }
  33. func (p *Peer) start() {
  34. if atomic.CompareAndSwapUint32(&p.started, 0, 1) {
  35. log.Debug("Starting %v", p)
  36. p.mconn.Start()
  37. }
  38. }
  39. func (p *Peer) stop() {
  40. if atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
  41. log.Debug("Stopping %v", p)
  42. p.mconn.Stop()
  43. }
  44. }
  45. func (p *Peer) IsOutbound() bool {
  46. return p.outbound
  47. }
  48. func (p *Peer) Send(chId byte, bytes ByteSlice) bool {
  49. if atomic.LoadUint32(&p.stopped) == 1 {
  50. return false
  51. }
  52. return p.mconn.Send(chId, bytes)
  53. }
  54. func (p *Peer) TrySend(chId byte, bytes ByteSlice) bool {
  55. if atomic.LoadUint32(&p.stopped) == 1 {
  56. return false
  57. }
  58. return p.mconn.TrySend(chId, bytes)
  59. }
  60. func (o *Peer) CanSend(chId byte) int {
  61. if atomic.LoadUint32(&p.stopped) == 1 {
  62. return 0
  63. }
  64. return p.mconn.CanSend(chId)
  65. }
  66. func (p *Peer) WriteTo(w io.Writer) (n int64, err error) {
  67. return String(p.Key).WriteTo(w)
  68. }
  69. func (p *Peer) String() string {
  70. if p.outbound {
  71. return fmt.Sprintf("P(->%v)", p.mconn)
  72. } else {
  73. return fmt.Sprintf("P(%v->)", p.mconn)
  74. }
  75. }
  76. func (p *Peer) Equals(other *Peer) bool {
  77. return p.Key == other.Key
  78. }