-
Notifications
You must be signed in to change notification settings - Fork 35
/
match.go
95 lines (81 loc) · 1.59 KB
/
match.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
package server
import (
"fmt"
"net"
"sync"
"time"
)
type SendConn struct {
id string
conn net.Conn
filename string
recvConnCh chan *RecvConn
}
func NewSendConn(id string, conn net.Conn, filename string) *SendConn {
return &SendConn{
id: id,
conn: conn,
filename: filename,
recvConnCh: make(chan *RecvConn),
}
}
type RecvConn struct {
id string
conn net.Conn
}
func NewRecvConn(id string, conn net.Conn) *RecvConn {
return &RecvConn{
id: id,
conn: conn,
}
}
type MatchController struct {
senders map[string]*SendConn
mu sync.Mutex
}
func NewMatchController() *MatchController {
return &MatchController{
senders: make(map[string]*SendConn),
}
}
// block until there is a same ID recv conn or timeout
func (mc *MatchController) DealSendConn(sc *SendConn, timeout time.Duration) error {
mc.mu.Lock()
if _, ok := mc.senders[sc.id]; ok {
mc.mu.Unlock()
return fmt.Errorf("id is repeated")
}
mc.senders[sc.id] = sc
mc.mu.Unlock()
select {
case <-sc.recvConnCh:
case <-time.After(timeout):
mc.mu.Lock()
if tmp, ok := mc.senders[sc.id]; ok && tmp == sc {
delete(mc.senders, sc.id)
}
mc.mu.Unlock()
return fmt.Errorf("timeout waiting recv conn")
}
return nil
}
func (mc *MatchController) DealRecvConn(rc *RecvConn) (filename string, err error) {
mc.mu.Lock()
sc, ok := mc.senders[rc.id]
if ok {
delete(mc.senders, rc.id)
}
mc.mu.Unlock()
if !ok {
err = fmt.Errorf("no target sender")
return
}
filename = sc.filename
select {
case sc.recvConnCh <- rc:
default:
err = fmt.Errorf("no target sender")
return
}
return
}