From 03fb54ab96114c4c681f74b6ba3493ada39b92a2 Mon Sep 17 00:00:00 2001 From: q191201771 <191201771@qq.com> Date: Sat, 31 Aug 2019 11:58:37 +0800 Subject: [PATCH] package connection: ModWriteBufSize --- README.md | 8 +++++--- pkg/connection/connection.go | 21 ++++++++++++--------- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2af51aa..e78f756 100644 --- a/README.md +++ b/README.md @@ -32,11 +32,11 @@ pkg/ ......源码包 |-- bele/ ......提供了大小端的转换操作 |-- bininfo/ ......将编译时的git版本号,时间,Go编译器信息打入程序中 |-- connection/ ......对 net.Conn 接口的二次封装 - |-- connstat/ ...... |-- errors/ ......错误处理相关 |-- log/ ......日志库 |-- unique/ ......对象唯一ID demo/ ......示例相关的代码 + |-- connstat/ ......简单测试 net.Conn.SetWriteDeadline 的性能 bin/ ......可执行文件编译输出目录 ``` @@ -44,6 +44,8 @@ bin/ ......可执行文件编译输出目录 无任何第三方依赖 -#### 其他 +#### 项目名 nezha 由来 -本仓库主要用于存放我自己写的一些Go基础库代码。目前服务于我的另一个项目: [lal](https:////github.com/q191201771/lal) +本仓库主要用于存放我自己写的一些 Go 基础库代码。目前只服务于我的另一个项目: [lal](https:////github.com/q191201771/lal) + +nezha 即 哪吒,希望本仓库以后能像三头六臂,有多种武器的哪吒一样,为我提供多种工具。 diff --git a/pkg/connection/connection.go b/pkg/connection/connection.go index afab97d..24688dc 100644 --- a/pkg/connection/connection.go +++ b/pkg/connection/connection.go @@ -16,21 +16,21 @@ type Connection interface { // 包含 interface net.Conn 的所有方法 net.Conn - // 额外提供的读方法 ReadAtLeast(buf []byte, min int) (n int, err error) ReadLine() (line []byte, isPrefix bool, err error) - // 额外提供的写方法 Printf(fmt string, v ...interface{}) (n int, err error) + + ModWriteBufSize(n int) } type Config struct { - // 如果不为0,则使用 buffer + // 如果不为0,则之后每次读/写使用 buffer 缓冲 ReadBufSize int WriteBufSize int // 如果不为0,则之后每次读/写都带超时 - ReadTimeoutMS int + ReadTimeoutMS int WriteTimeoutMS int } @@ -58,11 +58,14 @@ type connection struct { config Config } -// 为保证运行时性能,调用方需保证: -// 1. 调用 Config 方法时,不并行调用其它接口造成竞态读写属性 -// 2. 只能在使用无缓冲时切换成缓冲,如果已经有缓冲,则不能再次切换 -func (c *connection) Config(config Config) { - c.config = config +func (c *connection) ModWriteBufSize(n int) { + if c.config.WriteBufSize > 0 { + // 如果之前已经设置过写缓冲,直接 panic + // 这里改成 flush 后替换成新缓冲也行,暂时没这个必要 + panic(connectionErr) + } + c.config.WriteBufSize = n + c.w = bufio.NewWriterSize(c.Conn, n) } func (c *connection) ReadAtLeast(buf []byte, min int) (n int, err error) {