github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/swarm/pss/ping.go (about)

     1  
     2  //此源码被清华学神尹成大魔王专业翻译分析并修改
     3  //尹成QQ77025077
     4  //尹成微信18510341407
     5  //尹成所在QQ群721929980
     6  //尹成邮箱 yinc13@mails.tsinghua.edu.cn
     7  //尹成毕业于清华大学,微软区块链领域全球最有价值专家
     8  //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
     9  //
    10  //
    11  //
    12  //
    13  //
    14  //
    15  //
    16  //
    17  //
    18  //
    19  //
    20  //
    21  //
    22  //
    23  //
    24  
    25  //
    26  
    27  package pss
    28  
    29  import (
    30  	"context"
    31  	"errors"
    32  	"time"
    33  
    34  	"github.com/ethereum/go-ethereum/p2p"
    35  	"github.com/ethereum/go-ethereum/p2p/protocols"
    36  	"github.com/ethereum/go-ethereum/swarm/log"
    37  )
    38  
    39  //
    40  //
    41  type PingMsg struct {
    42  	Created time.Time
    43  Pong    bool //
    44  }
    45  
    46  type Ping struct {
    47  Pong bool      //
    48  OutC chan bool //
    49  InC  chan bool //
    50  }
    51  
    52  func (p *Ping) pingHandler(ctx context.Context, msg interface{}) error {
    53  	var pingmsg *PingMsg
    54  	var ok bool
    55  	if pingmsg, ok = msg.(*PingMsg); !ok {
    56  		return errors.New("invalid msg")
    57  	}
    58  	log.Debug("ping handler", "msg", pingmsg, "outc", p.OutC)
    59  	if p.InC != nil {
    60  		p.InC <- pingmsg.Pong
    61  	}
    62  	if p.Pong && !pingmsg.Pong {
    63  		p.OutC <- true
    64  	}
    65  	return nil
    66  }
    67  
    68  var PingProtocol = &protocols.Spec{
    69  	Name:       "psstest",
    70  	Version:    1,
    71  	MaxMsgSize: 1024,
    72  	Messages: []interface{}{
    73  		PingMsg{},
    74  	},
    75  }
    76  
    77  var PingTopic = ProtocolTopic(PingProtocol)
    78  
    79  func NewPingProtocol(ping *Ping) *p2p.Protocol {
    80  	return &p2p.Protocol{
    81  		Name:    PingProtocol.Name,
    82  		Version: PingProtocol.Version,
    83  		Length:  uint64(PingProtocol.MaxMsgSize),
    84  		Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
    85  			quitC := make(chan struct{})
    86  			pp := protocols.NewPeer(p, rw, PingProtocol)
    87  			log.Trace("running pss vprotocol", "peer", p, "outc", ping.OutC)
    88  			go func() {
    89  				for {
    90  					select {
    91  					case ispong := <-ping.OutC:
    92  						pp.Send(context.TODO(), &PingMsg{
    93  							Created: time.Now(),
    94  							Pong:    ispong,
    95  						})
    96  					case <-quitC:
    97  					}
    98  				}
    99  			}()
   100  			err := pp.Run(ping.pingHandler)
   101  			quitC <- struct{}{}
   102  			return err
   103  		},
   104  	}
   105  }