示例#1
0
文件: client.go 项目: himanshuo/tftp
func SendToServer(pathToFile string) {
	ServerAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:10001")
	CheckError(err)

	LocalAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	CheckError(err)

	Conn, err := net.DialUDP("udp", LocalAddr, ServerAddr)
	CheckError(err)
	defer Conn.Close()

	if err != nil {
		fmt.Println(pathToFile)
		fmt.Println(err)
	} else {
		//send write request
		tid := uint16(0)
		filename := filepath.Base(pathToFile)
		writePacket := packet.NewWritePacket(filename, tid, uint16(69))
		_, err = Conn.Write(writePacket.ToBytes())
		CheckError(err)

		p := make([]byte, 2048)
		_, err = bufio.NewReader(Conn).Read(p)
		CheckError(err)
		retPacket := packet.ToPacket(p)

		switch resp := retPacket.(type) {
		case packet.AckPacket:
			fmt.Println("acknowledge packet for some blocknum:", resp.BlockNum)
			//all is good. start sending data packets like normal
			SendDataPacketsToServer(pathToFile, Conn)
		case packet.ErrorPacket:
			fmt.Println("error packet with ErrMsg:", string(resp.ErrMsg))
		default:
			fmt.Println("returned packet for write request is erronous")
		}

	}
}
示例#2
0
func TestBytesToReadPacket(t *testing.T) {
	for i, test := range testReadPacket {
		ret := packet.ToPacket(test.bitVersion)
		if !reflect.DeepEqual(ret, test.packetVersion) {
			t.Errorf("Failed Test %d: ReadPacket: ToPacket(%v)=%v DESIRED: %v", i, test.bitVersion, ret, test.packetVersion)
		}
	}
}

//test WritePacket conversion to bytes
var testWritePacket = []struct {
	packetVersion packet.WritePacket
	bitVersion    []byte
	err           bool
}{
	{packet.NewWritePacket("HI"), stringToBytes("\x00" + string(packet.WRQ) + "HI" + "\x00" + packet.OCTECT + "\x00"), false},                                                                       //basic read
	{packet.NewWritePacket(""), stringToBytes("\x00" + string(packet.WRQ) + "" + "\x00" + packet.OCTECT + "\x00"), false},                                                                           //empty read
	{packet.NewWritePacket(nullTerminatedStringFromBytes(ALLBYTES)), stringToBytes("\x00" + string(packet.WRQ) + nullTerminatedStringFromBytes(ALLBYTES) + "\x00" + packet.OCTECT + "\x00"), false}, //all bytes
}

func TestWritePacketToBytes(t *testing.T) {
	for i, test := range testWritePacket {
		ret := test.packetVersion.ToBytes()

		same := true
		for j, b := range test.bitVersion {
			if ret[j] != b {
				same = false
			}
		}
		if !same {