StoreBackEnd/pkg/network/ClientMulticast.go

86 lines
2.0 KiB
Go
Raw Normal View History

package network
import (
"StoreBackEnd/pkg/protocol/repository"
"StoreBackEnd/pkg/protocol/rules/writers"
2022-02-26 18:08:52 +01:00
"fmt"
"net"
"time"
)
// CreateClientMulticast Méthode de construction d'un instance de la stuct ClientMulticast
2022-02-26 18:08:52 +01:00
func CreateClientMulticast(address string, domain string, port int, second time.Duration, repository *repository.ProtocolRepository) ClientMulticast {
return ClientMulticast{
2022-02-22 08:29:11 +01:00
address: address,
2022-02-26 18:08:52 +01:00
domain: domain,
port: port,
2022-02-22 08:29:11 +01:00
second: second,
repository: repository,
}
}
// ClientMulticast Cette structure représente une communication en multicast.
// TODO : Prévoir une fermeture de la connection (con.Close())
type ClientMulticast struct {
2022-02-26 18:08:52 +01:00
// address Adresse de multicast
address string
// address Domain de du StoreBackEnd
2022-02-26 18:08:52 +01:00
domain string
// port Port de connexion en unicast
port int
// second Temps en seconde entre chaque ping
second time.Duration
2022-02-22 08:29:11 +01:00
// Repository de protocol permettant de
repository *repository.ProtocolRepository
}
// Run Cette méthode démarre une commmunication multicast
func (client ClientMulticast) Run() {
addr, done := client.ResolveAddr()
if done {
return
}
con, done2 := client.DialUdp(addr)
if done2 {
return
}
cmd, correct := client.repository.ExecuteWriter(writers.HelloRuleName, client.domain, fmt.Sprintf("%d", client.port))
if !correct {
2022-02-22 10:03:52 +01:00
println("[ClientMulticast] Hello rule isn't correct (" + cmd + ")")
return
}
for {
_, _ = con.Write([]byte(cmd))
time.Sleep(time.Second * client.second)
}
}
// ResolveAddr Permet de résoude l'addresse
func (client ClientMulticast) ResolveAddr() (*net.UDPAddr, bool) {
addr, errResUdp := net.ResolveUDPAddr("udp", client.address)
if errResUdp != nil {
println(errResUdp.Error())
return nil, true
}
return addr, false
}
// DialUdp Ouvre une connection UDP
func (client ClientMulticast) DialUdp(addr *net.UDPAddr) (*net.UDPConn, bool) {
con, errDial := net.DialUDP("udp", nil, addr)
if errDial != nil {
println(errDial.Error())
return nil, true
}
return con, false
}