Exemple #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))
}
Exemple #2
0
// handle reading a local file and sending it to the server
func handlePut(filename, address string) error {
	f, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("Error opening file: %v", err)
	}
	defer f.Close()

	br := bufio.NewReader(f)

	serverAddr, conn, err := getAddrAndConn(address)
	if err != nil {
		return err
	}
	defer conn.Close()

	// Send WRQ packet
	wrq := common.RequestPacket{
		OpCode:   common.OpWRQ,
		Filename: filename,
		Mode:     "octet",
	}

	_, err = conn.WriteTo(wrq.ToBytes(), serverAddr)
	if err != nil {
		return fmt.Errorf("Error sending WRQ packet: %v", err)
	}

	// Get the ACK
	ackBuf := make([]byte, 4)
	_, remoteAddr, err := conn.ReadFrom(ackBuf)
	if err != nil {
		return fmt.Errorf("Error reading ACK packet: %v", err)
	}
	_, err = common.ParseAckPacket(ackBuf)
	if err != nil {
		return fmt.Errorf("Error parsing ACK packet: %v", err)
	}

	common.ReadFileLoop(br, conn, remoteAddr, common.BlockSize)

	return nil
}