forked from pratikju/transporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sender.go
95 lines (75 loc) · 1.63 KB
/
sender.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strconv"
"code.cloudfoundry.org/bytefmt"
)
// BUFFERSIZE is the smallest buffer size to be transferred over tcp network
const BUFFERSIZE = 1024
func startServer(addr, path string) {
go sendMulticastPacket()
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalln(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatalln(err)
}
if *recursive == true {
fileList := []string{}
_ = filepath.Walk(path, func(fpath string, f os.FileInfo, err error) error {
if fpath == path {
return nil
}
fileList = append(fileList, fpath)
return nil
})
for _, file := range fileList {
sendFile(conn, file)
}
} else {
sendFile(conn, path)
}
conn.Write(make([]byte, BUFFERSIZE))
conn.Close()
}
}
func sendFile(conn net.Conn, filePath string) {
file, err := os.Open(filePath)
if err != nil {
log.Println(err)
return
}
fileInfo, err := file.Stat()
if err != nil {
log.Println(err)
return
}
fileName := padString(fileInfo.Name(), 64)
fileSize := padString(strconv.FormatInt(fileInfo.Size(), 10), 10)
fmt.Println("Transferring : ", fileInfo.Name())
fmt.Println("Size : ", bytefmt.ByteSize(uint64(fileInfo.Size())))
fmt.Println("-------------------------------------------------------------------------")
conn.Write([]byte(fileSize))
conn.Write([]byte(fileName))
sendBuffer := make([]byte, BUFFERSIZE)
for {
_, err := file.Read(sendBuffer)
if err != nil {
if err != io.EOF {
return
}
break
}
conn.Write(sendBuffer)
}
return
}