-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_test.go
More file actions
85 lines (72 loc) · 1.93 KB
/
basic_test.go
File metadata and controls
85 lines (72 loc) · 1.93 KB
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
package netchan_test
import (
"fmt"
"io"
"log"
"github.com/pinkgopher/netchan"
)
func checkErrors(mn *netchan.Session) {
<-mn.Done()
if err := mn.Err(); err != netchan.EndOfSession {
log.Fatal(err)
}
}
type request struct {
N int
RespChName string
}
// emitIntegers sends the integers from 1 to n on net-chan "integers".
// conn would normally be a TCP-like connection to the other peer.
func client(conn io.ReadWriteCloser) {
mn := netchan.NewSession(conn)
go checkErrors(mn)
reqCh := make(chan request, 1)
err := mn.OpenSend("requests", reqCh)
if err != nil {
log.Fatal(err)
}
reqCh <- request{10, "response chan 0"}
respCh := make(chan int, 1)
err = mn.OpenRecv("response chan 0", respCh, 5)
if err != nil {
log.Fatal(err)
}
for i := range respCh {
fmt.Printf("%d ", i)
}
mn.Quit()
}
// sumIntegers receives the integers from net-chan "integers" and returns their sum.
func server(conn io.ReadWriteCloser) {
mn := netchan.NewSession(conn)
go checkErrors(mn)
reqCh := make(chan request, 1)
err := mn.OpenRecv("requests", reqCh, 5)
if err != nil {
log.Fatal(err)
}
req := <-reqCh
respCh := make(chan int, 1)
err = mn.OpenSend(req.RespChName, respCh)
if err != nil {
log.Fatal(err)
}
for i := 0; i < req.N; i++ {
respCh <- i
}
close(respCh)
// wait that client receives everything
// and shuts down, we will get EndOfSession
checkErrors(mn)
}
// This example shows a basic netchan session: two peers establish a connection and
// delegate its management to a netchan.Manager (one for peer); peer 1 opens a
// net-chan for sending; peer 2 opens the same net-chan (by name) for receiving;
// the peers communicate using the Go channels associated with the net-chans.
// Warning: this example does not include error handling.
func Example_requestResponse() {
sideA, sideB := newPipeConn() // a connection based on io.PipeReader/Writer
go client(sideA)
server(sideB)
// Output: 0 1 2 3 4 5 6 7 8 9
}