Hi, I am use udp protocol(must use it) to transfer file, I encountered a problem when receive byte stream and write to file.
As shown below:
type FileInfo struct {
Flen int64
Fname [24]byte
}
type Datapackage struct {
NContent [1000]byte
Finfo FileInfo
Datatype byte
NContentLen int64
}
func main(){
var dp Datapackage
var recvChan = make(chan []byte)
var buf :=new(bytes.Buffer)
p :=make([]byte, 1041) // 1041 is receive package len
ser, _ := net.ListentenUDP("udp", &addr)
for {
_ ,err := ser.Read(p)
buf.Write(p)
binary.Read(buf, binary.BigEndian, &dp)
if dp.Datatype =='A'{
filenamelen := bytes.IndexByte(dp.Finfo.Fname[:], 0)
filename := string(dp.Finfo.Fname[:filenamelen])
fp, err := os.Create(filename)
if err != nil {
fmt.Println(err)
}
go func(fp *os.File){
for {
wn, err := fp.Write(<-recvChan)
if err != nil {
fmt.Println(err)
}
if wn < 1000{
fmt.Println(wn)
break
}
}(fp)
close(recvChan)
fp.Close()
}
} else{
recvChan<-dp.NContent[:dp.NContentLen]
}
// }else{
// wn, err = fp.Write(dp.NContent[:dp.NContentLen])
// if err != nil {
// fmt.Println(err)
// }
// if wn < 1000{
// fp.Close()
// continue
// }
//}
}
}
now as above , there has two method to write data stream to file , one is usual way that has been Annotations, other is use channels. but when use channels , get the size of file is rigth ,but can not open (eg exe ,zip )correct ,and if not use channels , the file can open correct , I don't know why?
any help will appreciated.