/
read.go
59 lines (52 loc) · 993 Bytes
/
read.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
package client
import (
"errors"
tcpip "github.com/brewlin/net-protocol/protocol"
)
//Read 一次性读取完缓冲区数据
func (c *Client) Read() ([]byte, error) {
<-c.notifyC
var buf []byte
var err error
for {
v, _, e := c.ep.Read(&c.remote)
if e != nil {
err = e
break
}
buf = append(buf, v...)
}
if buf == nil {
return nil, err
}
return buf, nil
}
//Readn 读取固定字节的数据
func (c *Client) Readn(p []byte) (int, error) {
c.bufmu.Lock()
defer c.bufmu.Unlock()
//获取足够长度的字节
if len(p) > len(c.buf) {
for {
if len(p) <= len(c.buf) {
break
}
buf, _, err := c.ep.Read(&c.remote)
if err != nil {
if err == tcpip.ErrWouldBlock {
//阻塞等待数据
<-c.notifyC
continue
}
return 0, err
}
c.buf = append(c.buf, buf...)
}
}
if len(p) > len(c.buf) {
return 0, errors.New("package len is smaller than p need")
}
n := copy(p, c.buf)
c.buf = c.buf[len(p):]
return n, nil
}