-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtcpchan.go
119 lines (100 loc) · 2.34 KB
/
tcpchan.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// tcpchan project tcpchan.go
package tcpchan
import (
"encoding/gob"
"net"
)
// Wrapper for the payload (Value) so gob can serialize it
type data struct {
Value interface{}
}
// Creates a new channel listening on addr
func Listen(addr string) (chan interface{}, error) {
serv, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
ch := make(chan interface{})
go listen(serv, ch, false)
return ch, nil
}
// Creates a new channel connecting to addr
func Dial(addr string) (chan interface{}, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
ch := make(chan interface{})
go write(conn, ch)
return ch, nil
}
// Creates a new channel listening on addr
func ListenBlocking(addr string) (chan interface{}, error) {
serv, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
ch := make(chan interface{})
listen(serv, ch, true)
return ch, nil
}
// Listenes on a socket and starts writer for the first connection
func listen(serv net.Listener, ch chan interface{}, block bool) {
conn, err := serv.Accept()
if err != nil {
close(ch)
return
}
serv.Close()
if block {
go write(conn, ch)
} else {
write(conn, ch)
}
}
// Reads data from the connection conn and writes it into ch
func read(conn net.Conn, ch chan interface{}) {
defer close(ch) // make sure we close the channel when we stop reading
dec := gob.NewDecoder(conn)
buf := data{}
for {
err := dec.Decode(&buf) // try to de-serialize the data
if err != nil {
return
}
ch <- buf.Value // unpack the payload
}
}
// Handles writing to the remote channel and incoming data
func write(conn net.Conn, ch chan interface{}) {
defer conn.Close() // make sure we close the connection when we are done writing
in := make(chan interface{}, 256) // We need to buffer incoming data
go read(conn, in) // start the reader so we can use select
enc := gob.NewEncoder(conn)
cont:
for {
select {
case i, ok := <-ch: // seems we want to send data
if !ok {
return
}
enc.Encode(data{i})
case i, ok := <-in: // seems we received data
if !ok {
close(ch)
return
}
for {
select {
case ch <- i:
goto cont
case i, ok := <-ch: // seems we want to send data (so we are unable to write the received data)
if !ok {
return
}
enc.Encode(data{i})
}
}
}
}
}