func (e *Engine) connect(addr *net.TCPAddr) (*network.Device, error) { conn, err := net.DialTCP("tcp", nil, addr) if err != nil { return nil, err } log.Println("New outgoing TCP connection") return network.NewDevice(conn), nil }
func (e *Engine) broadcastIdentity() error { conn, err := net.Dial("udp", "255.255.255.255:"+strconv.Itoa(e.config.UdpPort)) if err != nil { return err } device := network.NewDevice(conn) err = e.sendIdentity(device) if err != nil { return err } conn.Close() return nil }
func (e *Engine) Listen() { go e.udpServer.Listen() go e.tcpServer.Listen() go e.broadcastIdentity() for { select { case udpPkg := <-e.udpServer.Incoming: raddr := udpPkg.RemoteAddress pkg := udpPkg.Package if pkg.Type == protocol.IdentityType { identity := pkg.Body.(*protocol.Identity) if identity.DeviceId == e.config.DeviceId { // Do not try to connect with ourselves continue } if _, ok := e.devices[identity.DeviceId]; ok { // Device already known continue } log.Println("New device discovered by UDP:", identity) device, err := e.connect(&net.TCPAddr{ IP: raddr.IP, Port: identity.TcpPort, Zone: raddr.Zone, }) if err != nil { log.Println("Could not open a TCP connection:", err) continue } setDeviceIdentity(device, identity) go e.handleDevice(device) } else { log.Println("Received a non-identity package on UDP connection", pkg) } case client := <-e.tcpServer.Joins: log.Println("New incoming TCP connection") device := network.NewDevice(client.Conn) go e.handleDevice(device) } } }