github.com/chain5j/chain5j-pkg@v1.0.7/eventbus/network_bus.go (about)

     1  package EventBus
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net"
     7  	"net/http"
     8  	"net/rpc"
     9  	"sync"
    10  )
    11  
    12  // NetworkBus - object capable of subscribing to remote event buses in addition to remote event
    13  // busses subscribing to it's local event bus. Compoed of a server and client
    14  type NetworkBus struct {
    15  	*Client
    16  	*Server
    17  	service   *NetworkBusService
    18  	sharedBus Bus
    19  	address   string
    20  	path      string
    21  }
    22  
    23  // NewNetworkBus - returns a new network bus object at the server address and path
    24  func NewNetworkBus(address, path string) *NetworkBus {
    25  	bus := new(NetworkBus)
    26  	bus.sharedBus = New()
    27  	bus.Server = NewServer(address, path, bus.sharedBus)
    28  	bus.Client = NewClient(address, path, bus.sharedBus)
    29  	bus.service = &NetworkBusService{&sync.WaitGroup{}, false}
    30  	bus.address = address
    31  	bus.path = path
    32  	return bus
    33  }
    34  
    35  // EventBus - returns wrapped event bus
    36  func (networkBus *NetworkBus) EventBus() Bus {
    37  	return networkBus.sharedBus
    38  }
    39  
    40  // NetworkBusService - object capable of serving the network bus
    41  type NetworkBusService struct {
    42  	wg      *sync.WaitGroup
    43  	started bool
    44  }
    45  
    46  // Start - helper method to serve a network bus service
    47  func (networkBus *NetworkBus) Start() error {
    48  	var err error
    49  	service := networkBus.service
    50  	clientService := networkBus.Client.service
    51  	serverService := networkBus.Server.service
    52  	if !service.started {
    53  		server := rpc.NewServer()
    54  		server.RegisterName("ServerService", serverService)
    55  		server.RegisterName("ClientService", clientService)
    56  		server.HandleHTTP(networkBus.path, "/debug"+networkBus.path)
    57  		l, e := net.Listen("tcp", networkBus.address)
    58  		if e != nil {
    59  			err = fmt.Errorf("listen error: %v", e)
    60  		}
    61  		service.wg.Add(1)
    62  		go http.Serve(l, nil)
    63  	} else {
    64  		err = errors.New("Server bus already started")
    65  	}
    66  	return err
    67  }
    68  
    69  // Stop - signal for the service to stop serving
    70  func (networkBus *NetworkBus) Stop() {
    71  	service := networkBus.service
    72  	if service.started {
    73  		service.wg.Done()
    74  		service.started = false
    75  	}
    76  }