github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/node/node_example_test.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 12:09:43</date>
    10  //</624342655177854976>
    11  
    12  
    13  package node_test
    14  
    15  import (
    16  	"fmt"
    17  	"log"
    18  
    19  	"github.com/ethereum/go-ethereum/node"
    20  	"github.com/ethereum/go-ethereum/p2p"
    21  	"github.com/ethereum/go-ethereum/rpc"
    22  )
    23  
    24  //sampleService是一个普通的网络服务,可以连接到
    25  //生命周期管理。
    26  //
    27  //实现node.service需要以下方法:
    28  //-protocols()[]p2p.protocol-服务可以通信的devp2p协议
    29  //-apis()[]rpc.api-服务希望在rpc通道上公开的api方法
    30  //-start()错误-节点准备启动服务时调用的方法
    31  //-stop()错误-节点终止服务时调用的方法
    32  type SampleService struct{}
    33  
    34  func (s *SampleService) Protocols() []p2p.Protocol { return nil }
    35  func (s *SampleService) APIs() []rpc.API           { return nil }
    36  func (s *SampleService) Start(*p2p.Server) error   { fmt.Println("Service starting..."); return nil }
    37  func (s *SampleService) Stop() error               { fmt.Println("Service stopping..."); return nil }
    38  
    39  func ExampleService() {
    40  //创建一个网络节点以运行具有默认值的协议。
    41  	stack, err := node.New(&node.Config{})
    42  	if err != nil {
    43  		log.Fatalf("Failed to create network node: %v", err)
    44  	}
    45  //创建并注册一个简单的网络服务。这是通过定义完成的
    46  //将实例化node.service的node.serviceconstructor。原因
    47  //工厂方法的方法是支持服务重新启动,而不依赖
    48  //单个实现对此类操作的支持。
    49  	constructor := func(context *node.ServiceContext) (node.Service, error) {
    50  		return new(SampleService), nil
    51  	}
    52  	if err := stack.Register(constructor); err != nil {
    53  		log.Fatalf("Failed to register service: %v", err)
    54  	}
    55  //启动整个协议栈,重新启动并终止
    56  	if err := stack.Start(); err != nil {
    57  		log.Fatalf("Failed to start the protocol stack: %v", err)
    58  	}
    59  	if err := stack.Restart(); err != nil {
    60  		log.Fatalf("Failed to restart the protocol stack: %v", err)
    61  	}
    62  	if err := stack.Stop(); err != nil {
    63  		log.Fatalf("Failed to stop the protocol stack: %v", err)
    64  	}
    65  //输出:
    66  //服务正在启动…
    67  //服务正在停止…
    68  //服务正在启动…
    69  //服务正在停止…
    70  }
    71