提交 4f34e0ec 作者: Jeromy

buffer msgio

License: MIT
Signed-off-by: 's avatarJeromy <jeromyj@gmail.com>
上级 c48f456b
package msgio package msgio
import ( import (
"bufio"
"errors" "errors"
"io" "io"
"sync" "sync"
...@@ -76,6 +77,7 @@ type ReadWriteCloser interface { ...@@ -76,6 +77,7 @@ type ReadWriteCloser interface {
// writer is the underlying type that implements the Writer interface. // writer is the underlying type that implements the Writer interface.
type writer struct { type writer struct {
W io.Writer W io.Writer
buf *bufio.Writer
lock sync.Locker lock sync.Locker
} }
...@@ -83,7 +85,7 @@ type writer struct { ...@@ -83,7 +85,7 @@ type writer struct {
// NewWriter wraps an io.Writer with a msgio framed writer. The msgio.Writer // NewWriter wraps an io.Writer with a msgio framed writer. The msgio.Writer
// will write the length prefix of every message written. // will write the length prefix of every message written.
func NewWriter(w io.Writer) WriteCloser { func NewWriter(w io.Writer) WriteCloser {
return &writer{W: w, lock: new(sync.Mutex)} return &writer{W: w, buf: bufio.NewWriter(w), lock: new(sync.Mutex)}
} }
func (s *writer) Write(msg []byte) (int, error) { func (s *writer) Write(msg []byte) (int, error) {
...@@ -100,8 +102,13 @@ func (s *writer) WriteMsg(msg []byte) (err error) { ...@@ -100,8 +102,13 @@ func (s *writer) WriteMsg(msg []byte) (err error) {
if err := WriteLen(s.W, len(msg)); err != nil { if err := WriteLen(s.W, len(msg)); err != nil {
return err return err
} }
_, err = s.W.Write(msg)
_, err = s.buf.Write(msg)
if err != nil {
return err return err
}
return s.buf.Flush()
} }
func (s *writer) Close() error { func (s *writer) Close() error {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论