Posted on 2013-08-02 10:11
oathleo 阅读(1176)
评论(0) 编辑 收藏 所属分类:
Golang
golang socket 读取长数据
1 func read(conn net.Conn, length int) ([]byte, error) {
2 data := make([]byte, length)
3 buf_size := 8
4 buf := make([]byte, buf_size)
5 i := 0
6 for {
7 if length < buf_size {
8 remain := make([]byte, length)
9 _, err := conn.Read(remain)
10 if err != nil {
11 return nil, err
12 }
13 copy(data[i:(i+length)], remain[:])
14 return data, nil
15 } else {
16 _, err := conn.Read(buf)
17 if err != nil {
18 return nil, err
19 }
20 copy(data[i:(i+buf_size)], buf[:])
21 i += buf_size
22 }
23 length -= buf_size
24 }
25 return data, nil
26 }
上面的
_, err := conn.Read(buf) 不能确保读完,所以修复成下面的代码func read(conn net.Conn, length int) ([]byte, error) {
data := make([]byte, length)
buf_size := 1024
buf := make([]byte, buf_size)
i := 0
for {
if length < buf_size {
if length == 0 {
return data, nil
}
remain := make([]byte, length)
r, err := conn.Read(remain)
if err != nil {
return nil, err
}
copy(data[i:(i+r)], remain[0:r])
i += r
length -= r
} else {
r, err := conn.Read(buf)
if err != nil {
return nil, err
}
copy(data[i:(i+r)], buf[0:r])
i += r
length -= r
}
}
return data, nil
}