-
Notifications
You must be signed in to change notification settings - Fork 3
/
server_conn.go
92 lines (75 loc) · 1.63 KB
/
server_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
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
package rudp
import (
"io"
"net"
"sync"
"time"
"github.com/pion/logging"
)
type serverConn struct {
conn net.PacketConn
remAddr net.Addr
readCh chan []byte
closed bool
mutex sync.RWMutex
log logging.LeveledLogger
}
func newServerConn(conn net.PacketConn, remAddr net.Addr, log logging.LeveledLogger) *serverConn {
return &serverConn{
conn: conn,
remAddr: remAddr,
readCh: make(chan []byte, 1024),
log: log,
}
}
func (c *serverConn) Read(b []byte) (n int, err error) {
data, ok := <-c.readCh
if !ok {
return 0, io.EOF
}
c.log.Debugf("serverConn: read %d bytes", len(data))
if len(b) < len(data) {
return 0, io.ErrShortBuffer
}
bytesCopied := copy(b, data)
c.log.Debugf("serverConn: bytesCopied=%d", bytesCopied)
return bytesCopied, nil
}
func (c *serverConn) Write(b []byte) (n int, err error) {
return c.conn.WriteTo(b, c.remAddr)
}
func (c *serverConn) Close() error {
c.handleInbound(nil)
return nil
}
func (c *serverConn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *serverConn) RemoteAddr() net.Addr {
return c.remAddr
}
func (c *serverConn) SetDeadline(t time.Time) error {
return nil // unused
}
func (c *serverConn) SetReadDeadline(t time.Time) error {
return nil // unused
}
func (c *serverConn) SetWriteDeadline(t time.Time) error {
return nil // unused
}
func (c *serverConn) handleInbound(data []byte) {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.closed {
return
}
if data == nil {
close(c.readCh)
c.closed = true
return
}
c.log.Debugf("serverConn: handleInboud: %d bytes", len(data))
buf := make([]byte, len(data))
copy(buf, data)
c.readCh <- buf
}