package network import ( "StoreBackEnd/pkg/protocol/repository" "StoreBackEnd/pkg/protocol/rules/writers" "StoreBackEnd/pkg/utils" "fmt" "net" "time" ) // CreateClientMulticast Méthode de construction d'un instance de la stuct ClientMulticast func CreateClientMulticast(netInterface string, address string, domain string, port int, second time.Duration, repository *repository.ProtocolRepository) ClientMulticast { return ClientMulticast{ netInter: netInterface, address: address, domain: domain, port: port, 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 { // netInter Interface réseaux multicast netInter string // address Adresse de multicast address string // address Domain de du StoreBackEnd domain string // port Port de connexion en unicast port int // second Temps en seconde entre chaque ping second time.Duration // repository de protocol permettant de repository *repository.ProtocolRepository } // Run Cette méthode démarre une commmunication multicast func (client ClientMulticast) Run() { // Resolve multicast addr rAddr, failedRA := client.ResolveAddr() if failedRA { return } // Resolve interface addr lAddr, failedRIA := ResolveInterfaceAddr(client.netInter) if failedRIA { println("Error : No IPv4 found in interface") return } // Init UDP server flux con, failedDU := client.DialUdp(lAddr, rAddr) if failedDU { return } writerResult := client.repository.ExecuteWriter(writers.HelloRulePrefix, client.domain, fmt.Sprintf("%d", client.port)) if writerResult == nil { println("[ClientMulticast] Hello rule isn't correct") return } for { _, _ = con.Write([]byte(writerResult.Cmd)) time.Sleep(time.Second * client.second) } } // ResolveAddr Permet de résoude l'addresse multicast func (client ClientMulticast) ResolveAddr() (*net.UDPAddr, bool) { addr, err := net.ResolveUDPAddr("udp", client.address) if err != nil { println(err.Error()) return nil, true } return addr, false } // ResolveInterfaceAddr Resolves the network interface address. func ResolveInterfaceAddr(inter string) (*net.UDPAddr, bool) { ip, err := utils.RetrieveIPv4FromInterface(inter) if err != nil { println("Error while loading interface : " + err.Error()) return nil, true } println("Selected IP for multicast : " + ip.String()) return &net.UDPAddr{IP: ip}, false } // DialUdp Ouvre une connection UDP func (client ClientMulticast) DialUdp(lAddr *net.UDPAddr, rAddr *net.UDPAddr) (*net.UDPConn, bool) { con, errDial := net.DialUDP("udp", lAddr, rAddr) if errDial != nil { println(errDial.Error()) return nil, true } return con, false }