71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package network
|
|
|
|
import (
|
|
"_StorBackEnd/pkg/protocol/repository"
|
|
"net"
|
|
"time"
|
|
)
|
|
|
|
// CreateClientMulticast Méthode de construction d'un instance de la stuct ClientMulticast
|
|
func CreateClientMulticast(address string, second time.Duration, repository *repository.ProtocolRepository) ClientMulticast {
|
|
return ClientMulticast{
|
|
address: address,
|
|
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 {
|
|
// address Adresse de multicast (address:port)
|
|
address string
|
|
|
|
// 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 (cMult ClientMulticast) Run() {
|
|
addr, done := cMult.ResolveAddr()
|
|
if done {
|
|
return
|
|
}
|
|
|
|
con, done2 := cMult.DialUdp(addr)
|
|
if done2 {
|
|
return
|
|
}
|
|
|
|
for {
|
|
con.Write([]byte("Hello"))
|
|
time.Sleep(time.Second * cMult.second)
|
|
}
|
|
|
|
}
|
|
|
|
// ResolveAddr Permet de résoude l'addresse
|
|
func (cMult ClientMulticast) ResolveAddr() (*net.UDPAddr, bool) {
|
|
addr, errResUdp := net.ResolveUDPAddr("udp", cMult.address)
|
|
|
|
if errResUdp != nil {
|
|
println(errResUdp.Error())
|
|
return nil, true
|
|
}
|
|
|
|
return addr, false
|
|
}
|
|
|
|
// DialUdp Ouvre une connection UDP
|
|
func (cMult 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
|
|
}
|