Exemplo n.º 1
0
func (s *UdpServer) Listen() {
	log.Println("Creating UDP server with address", s.address)

	addr, err := net.ResolveUDPAddr("udp", s.address)
	if err != nil {
		log.Fatal("Cannot resolve UDP address:", err)
	}
	ln, err := net.ListenUDP("udp", addr)
	if err != nil {
		log.Fatal("Cannot start UDP server:", err)
	}

	defer ln.Close()

	for {
		buffer := make([]byte, 2048) // TODO
		n, raddr, err := ln.ReadFromUDP(buffer)
		if err != nil {
			log.Fatal("Cannot read from remote:", err)
		}

		pkgBin := bytes.Trim(buffer[0:n], "\n")
		pkg, err := protocol.Unserialize(pkgBin)
		if err != nil {
			log.Fatal("Cannot parse package:", err)
		}

		s.Incoming <- UdpPackage{RemoteAddress: raddr, Package: pkg}
	}
}
Exemplo n.º 2
0
func (d *Device) Listen() {
	defer (func() {
		d.conn.Close()
		close(d.Incoming)
	})()

	scanner := bufio.NewScanner(d.conn)
	for scanner.Scan() {
		pkg, err := protocol.Unserialize(scanner.Bytes())
		if err != nil {
			log.Println("Cannot parse package:", err)
			break
		}

		d.Incoming <- pkg
	}
}