2 Star 15 Fork 10

北京小程科技有限公司/Go通用工具

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
read_conn.go 829 Bytes
一键复制 编辑 原始数据 按行查看 历史
package transfer
import (
"errors"
"fmt"
"net"
)
// 默认最大长度20M
const DefaultMaxLength = uint32(1024 * 1024 * 20)
// 从连接中读取数据,不判断最大长度
func ReadConn(
conn net.Conn,
length uint32,
) (buf []byte, err error) {
return ReadConnMaxLength(conn, length, 0)
}
// 从连接中读取数据,判断最大长度
func ReadConnMaxLength(
conn net.Conn,
length uint32,
maxLength uint32,
) (buf []byte, err error) {
if conn == nil {
err = errors.New("连接不能为空")
return
}
if maxLength > 0 && length > maxLength {
err = fmt.Errorf("数据长度过大,疑似包传输异常")
return
}
buf = make([]byte, length)
start := 0
for {
cnt, e := conn.Read(buf[start:])
if e != nil {
err = e
return
}
if cnt > 0 {
start += cnt
} else {
return
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xiaochengtech/common.git
git@gitee.com:xiaochengtech/common.git
xiaochengtech
common
Go通用工具
82269be32710

搜索帮助