forked from pebbe/zmq4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileio1.go
98 lines (83 loc) · 2.1 KB
/
fileio1.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
96
97
98
// File Transfer model #1
//
// In which the server sends the entire file to the client in
// large chunks with no attempt at flow control.
package main
import (
zmq "github.com/pebbe/zmq4"
"fmt"
"io"
"os"
)
const (
CHUNK_SIZE = 250000
)
func client_thread(pipe chan<- string) {
dealer, _ := zmq.NewSocket(zmq.DEALER)
dealer.Connect("tcp://127.0.0.1:6000")
dealer.Send("fetch", 0)
total := 0 // Total bytes received
chunks := 0 // Total chunks received
for {
frame, err := dealer.RecvBytes(0)
if err != nil {
break // Shutting down, quit
}
chunks++
size := len(frame)
total += size
if size == 0 {
break // Whole file received
}
}
fmt.Printf("%v chunks received, %v bytes\n", chunks, total)
pipe <- "OK"
}
// The server thread reads the file from disk in chunks, and sends
// each chunk to the client as a separate message. We only have one
// test file, so open that once and then serve it out as needed:
func server_thread() {
file, err := os.Open("testdata")
if err != nil {
panic(err)
}
router, _ := zmq.NewSocket(zmq.ROUTER)
// Default HWM is 1000, which will drop messages here
// since we send more than 1,000 chunks of test data,
// so set an infinite HWM as a simple, stupid solution:
router.SetRcvhwm(0)
router.SetSndhwm(0)
router.Bind("tcp://*:6000")
for {
// First frame in each message is the sender identity
identity, err := router.Recv(0)
if err != nil {
break // Shutting down, quit
}
// Second frame is "fetch" command
command, _ := router.Recv(0)
if command != "fetch" {
panic("command != \"fetch\"")
}
chunk := make([]byte, CHUNK_SIZE)
for {
n, _ := io.ReadFull(file, chunk)
router.SendMessage(identity, chunk[:n])
if n == 0 {
break // Always end with a zero-size frame
}
}
}
file.Close()
}
// The main task starts the client and server threads; it's easier
// to test this as a single process with threads, than as multiple
// processes:
func main() {
pipe := make(chan string)
// Start child threads
go server_thread()
go client_thread(pipe)
// Loop until client tells us it's done
<-pipe
}