forked from pratikju/transporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
receiver.go
73 lines (57 loc) · 1.4 KB
/
receiver.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
package main
import (
"fmt"
"io"
"log"
"net"
"os"
"strconv"
"strings"
"time"
"code.cloudfoundry.org/bytefmt"
)
func startClient() {
senderIP := getSenderIP()
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", senderIP.String(), port))
if err != nil {
log.Fatalln(err)
}
receiveFile(conn)
}
func receiveFile(conn net.Conn) {
defer conn.Close()
bufferFileName := make([]byte, 64)
bufferFileSize := make([]byte, 10)
for {
conn.Read(bufferFileSize)
fileSize, _ := strconv.ParseInt(strings.Trim(string(bufferFileSize), ":"), 10, 64)
if fileSize == 0 {
break
}
conn.Read(bufferFileName)
fileName := strings.Trim(string(bufferFileName), ":")
start := time.Now()
receivedFile, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
}
var receivedBytes int64
var remainingSize int64
for {
remainingSize = fileSize - receivedBytes
if remainingSize < BUFFERSIZE {
io.CopyN(receivedFile, conn, remainingSize)
conn.Read(make([]byte, (BUFFERSIZE - remainingSize)))
break
}
io.CopyN(receivedFile, conn, BUFFERSIZE)
receivedBytes += BUFFERSIZE
}
receivedFile.Close()
elapsed := time.Since(start)
fmt.Println("Transferred : ", fileName)
fmt.Println("Size : ", bytefmt.ByteSize(uint64(fileSize)))
fmt.Println("Time taken : ", elapsed)
fmt.Println("-------------------------------------------------------------------------")
}
}