-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceiver.go
81 lines (72 loc) · 1.69 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
74
75
76
77
78
79
80
81
package main
import (
"bufio"
"fmt"
"io"
"net"
"os"
)
func main() {
serverIP := "127.0.0.1"
conn, err := net.Dial("tcp", serverIP+":8080")
if err != nil {
fmt.Printf("Error connecting to server: %v\n", err)
os.Exit(1)
}
defer conn.Close()
// Send client type
_, err = fmt.Fprint(conn, "RECEIVER\n")
if err != nil {
fmt.Printf("Error sending client type: %v\n", err)
os.Exit(1)
}
// Receive session ID
scanner := bufio.NewScanner(conn)
if scanner.Scan() {
sessionID := scanner.Text()
fmt.Printf("Session ID: %s\n", sessionID)
} else {
fmt.Println("Failed to receive session ID.")
os.Exit(1)
}
// Wait for file transfer
fmt.Println("Waiting for file transfer to start...")
var outputFile *os.File
totalBytesReceived := 0
buffer := make([]byte, 4096)
for {
n, err := conn.Read(buffer)
if n > 0 {
// Create the file only when data is received
if outputFile == nil {
outputFile, err = os.Create("received_file")
if err != nil {
fmt.Printf("Error creating file: %v\n", err)
os.Exit(1)
}
defer outputFile.Close()
fmt.Println("Transfer started. Writing to 'received_file'...")
}
_, writeErr := outputFile.Write(buffer[:n])
if writeErr != nil {
fmt.Printf("Error writing to file: %v\n", writeErr)
break
}
totalBytesReceived += n
fmt.Printf("Received %d bytes.\n", n)
}
if err == io.EOF {
fmt.Println("Connection closed by server.")
break
}
if err != nil {
fmt.Printf("Error reading from connection: %v\n", err)
break
}
}
if totalBytesReceived > 0 {
fmt.Printf("Transfer finished. Total bytes received: %d\n", totalBytesReceived)
} else {
fmt.Println("No data received. Transfer aborted.")
}
}