Documentation
¶
Overview ¶
All interaction with the library takes place through an instance of Service, which is created in the following manner:
s := sdiscovery.New(ServiceConfig{
PollInterval: 1*time.Minute,
PingInterval: 2*time.Second,
PeerTimeout: 8*time.Second,
Port: 1234,
ID: "machine01",
UserData: []byte("data"),
})
At this point, the service will begin sending broadcast and multicast packets on all appropriate network interfaces and listening for packets from other peers. The service provides two channels that provide notifications when peers are added or removed:
for {
select {
case id := <- s.PeerAdded:
fmt.Printf("Peer %s added!\n", id)
case id := <- s.PeerRemoved:
fmt.Printf("Peer %s removed!\n", id)
}
}
Once you have a peer ID, you can use it to retrieve the custom user data for that specific peer:
data, _ := s.PeerUserData(id)
fmt.Printf("UserData: %s\n", data)
If you need to connect to the peer, it is possible to obtain a slice of IP addresses for the peer. As packets are received from the peer, the IP address and timestamp are recored. This allows the service to determine the best IP address for contacting the peer.
addrs, _ := s.PeerAddrs(id)
for _, a := range addrs {
fmt.Printf("- %s", a)
}
Note that you may want to filter the addresses since the slice may contain both IPv4 and IPv6 addresses.
The service can be shutdown by invoking the Stop() method:
s.Stop()
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Service ¶
type Service struct {
PeerAdded chan string // indicates that a new peer was found
PeerRemoved chan string // indicates that an existing peer has timed out
// contains filtered or unexported fields
}
Service sends and receives packets on local network interfaces in order to discover other peers providing the service and announce its presence.
func New ¶
func New(config ServiceConfig) *Service
Create a new Service instance with the specified configuration.
func (*Service) PeerAddrs ¶
Obtain a sorted slice of IP addresses to use for connecting to the specified peer. The first IP address is the one that has received the most packets recently.
func (*Service) PeerUserData ¶
Obtain the custom user data provided by the specified peer.
type ServiceConfig ¶
type ServiceConfig struct {
PollInterval time.Duration // time between polling for network interfaces
PingInterval time.Duration // time between pings on the network
PeerTimeout time.Duration // time after which a peer is considered unreachable
Port int // port used for broadcast and multicast
ID string // unique identifier for the current machine
UserData []byte // data sent with each packet to other peers
}
ServiceConfig contains the parameters that control how the service behaves. Note that it is important to keep the size of UserData to a minimum since the entire struct is sent in each packet. Any modifications to this struct after passing it to New() will be ignored.