github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/network/rpc/client_example_test.go (about)

     1  package rpc_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"math/big"
     7  	"time"
     8  
     9  	"github.com/neatio-net/neatio/network/rpc"
    10  )
    11  
    12  type Block struct {
    13  	Number *big.Int
    14  }
    15  
    16  func ExampleClientSubscription() {
    17  	client, _ := rpc.Dial("ws://127.0.0.1:8485")
    18  	subch := make(chan Block)
    19  
    20  	go func() {
    21  		for i := 0; ; i++ {
    22  			if i > 0 {
    23  				time.Sleep(2 * time.Second)
    24  			}
    25  			subscribeBlocks(client, subch)
    26  		}
    27  	}()
    28  
    29  	for block := range subch {
    30  		fmt.Println("latest block:", block.Number)
    31  	}
    32  }
    33  
    34  func subscribeBlocks(client *rpc.Client, subch chan Block) {
    35  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    36  	defer cancel()
    37  
    38  	sub, err := client.EthSubscribe(ctx, subch, "newHeads")
    39  	if err != nil {
    40  		fmt.Println("subscribe error:", err)
    41  		return
    42  	}
    43  
    44  	var lastBlock Block
    45  	if err := client.CallContext(ctx, &lastBlock, "eth_getBlockByNumber", "latest"); err != nil {
    46  		fmt.Println("can't get latest block:", err)
    47  		return
    48  	}
    49  	subch <- lastBlock
    50  
    51  	fmt.Println("connection lost: ", <-sub.Err())
    52  }