-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceive.go
82 lines (70 loc) · 1.75 KB
/
receive.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
package main
import (
"io"
"log"
"net"
"os"
"strconv"
"strings"
"time"
)
var (
receivedBytes int64
bufferFileSize byte
bufferFilename byte
bufferFileType byte
)
// Main function for receive.go
func receive() {
ip := getIP()
println(ip + PORT)
connection, err := net.Dial("tcp", ip+PORT)
handleErr(err, "")
log.Println("Connected")
// connection.RemoteAddr()
if beginClient(connection) {
log.Println("Downloaded")
} else {
log.Println("Unable to download")
}
}
// Catch a single file transfer
func catchTransfer(fileName string, fileSize int64, connection net.Conn) {
receivedBytes = 0
newFile, err := os.Create(fileName)
handleErr(err, "")
// Writing to the new file in chunks
for receivedBytes < fileSize {
// Less than one chunk left
if (fileSize - receivedBytes) < BUFFERSIZE {
lastChunk := fileSize - receivedBytes
io.CopyN(newFile, connection, lastChunk)
receivedBytes += lastChunk
break
}
io.CopyN(newFile, connection, BUFFERSIZE)
receivedBytes += BUFFERSIZE
}
}
// Begin server for tcp connection
func beginClient(connection net.Conn) bool {
bufferFileName := make([]byte, 64)
bufferFileSize := make([]byte, 10)
for {
connection.Read(bufferFileSize)
connection.Read(bufferFileName)
if string(bufferFileType) == "d" {
}
fileSize, _ := strconv.ParseInt(strings.Trim(string(bufferFileSize), ":"), 10, 64)
fileName := strings.Trim(string(bufferFileName), ":")
log.Println("Beginning transfer")
log.Println("Downloading " + fileName)
log.Println("FileName:\t\t", fileName)
log.Println("FileSize:\t\t", fileSize, "bytes")
initialTime := time.Now()
catchTransfer(fileName, fileSize, connection)
totalTime := time.Since(initialTime)
log.Print("Total time:\t\t ", totalTime)
return true
}
}