Exemplo n.º 1
0
func handleReadRequest(remoteAddress net.Addr, filename string) {
	start := time.Now()
	log.Println("Handling RRQ for", filename)

	conn, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4zero,
		Port: 0,
	})
	if err != nil {
		log.Println("Error listening", err)
		return
	}
	defer conn.Close()

	f, err := os.Open(filename)
	if err != nil {
		log.Println(err)
		if os.IsNotExist(err) {
			common.SendError(1, "File not found", conn, remoteAddress)
			return
		}
		common.SendError(0, err.Error(), conn, remoteAddress)
		return
	}
	defer f.Close()

	br := bufio.NewReader(f)
	bytesRead, err := common.ReadFileLoop(br, conn, remoteAddress, common.BlockSize)
	if err != nil {
		log.Println("Error handling read:", err)
	}
	log.Printf("Done sending %s. %d bytes in %v", filename, bytesRead, time.Since(start))
}
Exemplo n.º 2
0
func handleWriteRequest(remoteAddress net.Addr, filename string) {
	log.Println("Handling WRQ")

	// Don't use DialUDP here, see https://groups.google.com/forum/#!topic/golang-nuts/Mb3MS9Khito
	conn, err := net.ListenUDP("udp", nil)
	if err != nil {
		log.Println(err)
		return
	}
	defer conn.Close()

	f, err := os.Create(filename)
	if err != nil {
		log.Println(err)
		// TODO: This error should indicate what went wrong
		common.SendError(0, err.Error(), conn, remoteAddress)
		return
	}
	defer fileCleanup(f)

	bw := bufio.NewWriter(f)
	defer bw.Flush()

	tid := uint16(0)

	// Acknowledge WRQ
	ack := common.CreateAckPacket(tid)
	_, err = conn.WriteTo(ack, remoteAddress)
	if err != nil {
		log.Println(err)
		return
	}

	err = common.WriteFileLoop(bw, conn, remoteAddress)
	if err != nil {
		log.Println("Error sending file:", err)
	}
	log.Println("Seccesfully received:", filename)
}