connection

package
v0.20.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 6, 2021 License: MIT Imports: 9 Imported by: 5

Documentation

Overview

package connection

注意,这个package还在开发中

对 net.Conn 接口的二次封装,目的有两个: 1. 在流媒体传输这种特定的长连接场景下提供更方便、高性能的接口 2. 便于后续将TCPConn替换成其他传输协议

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrConnectionPanic = errors.New("naza.connection: using in a wrong way")
	ErrClosedAlready   = errors.New("naza.connection: connection closed already")
	ErrWriteChanFull   = errors.New("naza.connection: write channel full")
)

Functions

This section is empty.

Types

type Connection

type Connection interface {
	// Conn 包含net.Conn interface的所有方法
	//
	// Read(b []byte) (n int, err error)
	// Write(b []byte) (n int, err error)
	// // Close 允许调用多次
	// //
	// Close() error
	// LocalAddr() net.Addr
	// RemoteAddr() net.Addr
	// SetDeadline(t time.Time) error
	// SetReadDeadline(t time.Time) error
	// SetWriteDeadline(t time.Time) error
	//
	net.Conn

	ReadAtLeast(buf []byte, min int) (n int, err error)
	ReadLine() (line []byte, isPrefix bool, err error) // 只有设置了ReadBufSize才可以使用这个方法

	// 如果使用了bufio写缓冲,则将缓冲中的数据发送出去
	// 如果使用了channel异步发送,则阻塞等待,直到之前channel中的数据全部发送完毕
	// 一般在Close前,想要将剩余数据发送完毕时调用
	Flush() error

	// Done 阻塞直到连接关闭或发生错误
	//
	// 注意,向上层严格保证,消息发送后,后续Read,Write等调用都将失败
	//
	// 注意,向上层严格保证,消息只发送一次
	//
	// @return 返回nil则是本端主动调用Close关闭
	//
	Done() <-chan error

	// TODO chef: 这几个接口是否不提供
	// Mod类型函数不加锁,需要调用方保证不发生竞态调用
	ModWriteChanSize(n int)
	ModWriteBufSize(n int)
	ModReadTimeoutMs(n int)
	ModWriteTimeoutMs(n int)

	// 连接上读取和发送的字节总数。
	// 注意,如果是异步发送,发送字节统计的是调用底层write的值,而非上层调用Connection发送的值
	// 也即不包含Connection中的发送缓存部分,但是可能包含内核socket发送缓冲区的值。
	GetStat() Stat
}

func New

func New(conn net.Conn, modOptions ...ModOption) Connection

type ModOption

type ModOption func(option *Option)

type Option

type Option struct {
	// 如果不为0,则之后每次读/写使用bufio的缓冲
	ReadBufSize  int
	WriteBufSize int

	// 如果不为0,则之后每次读/写都带超时
	ReadTimeoutMs  int
	WriteTimeoutMs int

	// 如果不为0,则写使用channel将数据发送到后台协程中发送
	WriteChanSize int

	// 使用channel发送数据时,channel满了时Write函数的行为
	// WriteChanFullBehaviorReturnError 返回错误
	// WriteChanFullBehaviorBlock 阻塞直到向channel写入成功
	WriteChanFullBehavior WriteChanFullBehavior
}

type Stat

type Stat struct {
	ReadBytesSum  uint64
	WroteBytesSum uint64
}

type StatAtomic

type StatAtomic struct {
	ReadBytesSum  nazaatomic.Uint64
	WroteBytesSum nazaatomic.Uint64
}

type WriteChanFullBehavior

type WriteChanFullBehavior int
const (
	WriteChanFullBehaviorReturnError WriteChanFullBehavior = iota + 1
	WriteChanFullBehaviorBlock
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL