-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathconn.go
60 lines (48 loc) · 1.16 KB
/
conn.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
package h2conn
import (
"context"
"io"
"sync"
)
// Conn is client/server symmetric connection.
// It implements the io.Reader/io.Writer/io.Closer to read/write or close the connection to the other side.
// It also has a Send/Recv function to use channels to communicate with the other side.
type Conn struct {
r io.Reader
wc io.WriteCloser
ctx context.Context
cancel context.CancelFunc
wLock sync.Mutex
rLock sync.Mutex
}
// Done returns a channel that is closed when the other side closes the connection.
func (c *Conn) Done() <-chan struct{} {
return c.ctx.Done()
}
func newConn(ctx context.Context, r io.Reader, wc io.WriteCloser) *Conn {
ctx, cancel := context.WithCancel(ctx)
c := &Conn{
r: r,
wc: wc,
ctx: ctx,
cancel: cancel,
}
return c
}
// Write writes data to the connection
func (c *Conn) Write(data []byte) (int, error) {
c.wLock.Lock()
defer c.wLock.Unlock()
return c.wc.Write(data)
}
// Read reads data from the connection
func (c *Conn) Read(data []byte) (int, error) {
c.rLock.Lock()
defer c.rLock.Unlock()
return c.r.Read(data)
}
// Close closes the connection
func (c *Conn) Close() error {
c.cancel()
return c.wc.Close()
}