conn

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: BSD-3-Clause Imports: 6 Imported by: 0

README

Conn - Enhanced Network Connection Library

Go Report Card GoDoc Version GitHub GitHub go.mod Go version

Conn is a Go library that extends net.Conn with additional functionalities including timeout reading, rate limiting, statistics, and bidirectional data exchange.

Features

  • Rate Limiting: Token bucket algorithm for controlling read/write speed
  • Statistics: Real-time monitoring of sent/received bytes
  • Bidirectional Data Exchange: Efficient data forwarding between connections
  • Protocol Support: Full support for both TCP and UDP protocols
  • Timeout Handling: Configurable read timeouts for connections
  • Thread Safety: Atomic operations for statistics and rate limiting

Installation

# Install latest version
go get github.com/vistone/conn

# Install specific version (v1.0.2)
go get github.com/vistone/conn@v1.0.2

Version

Current version: v1.0.2

Go Version Requirement

Go 1.25.4 or higher is required to use this library.

Go Version Compatibility

This library is tested and compatible with:

  • Go 1.25.4+ (recommended)
  • Go 1.21+ (minimum required for min() function support)

Important Notes:

  • The library uses Go's built-in min() function which was introduced in Go 1.21
  • If you're using Go 1.20 or earlier, you'll need to upgrade to at least Go 1.21
  • For best performance and latest features, we recommend using Go 1.25.4 or later
Upgrading Go Version

If you need to upgrade your Go version:

# Check current Go version
go version

# Download and install latest Go from https://go.dev/dl/
# Or use your system's package manager

# Verify installation
go version

Core Components

1. RateLimiter

Implements token bucket algorithm for rate limiting read/write operations:

// Create a rate limiter (1000 bytes/second read, 2000 bytes/second write)
limiter := conn.NewRateLimiter(1000, 2000)

// Wait for read tokens
limiter.WaitRead(100)

// Wait for write tokens
limiter.WaitWrite(200)

// Dynamically adjust rates
limiter.SetRate(1500, 3000)

// Reset rate limiter
limiter.Reset()
2. StatConn

Wraps net.Conn to provide byte counting and rate limiting:

var rx, tx uint64
conn := conn.NewStatConn(netConn, &rx, &tx, rateLimiter)

// Read/write data normally
n, err := conn.Read(buffer)
n, err = conn.Write(data)

// Get statistics
received := conn.GetRX()
sent := conn.GetTX()
total := conn.GetTotal()

// Reset statistics
conn.Reset()

// Access underlying connection
rawConn := conn.GetConn()

// Get rate limiter
rate := conn.GetRate()

// Check connection type
isTCP := conn.IsTCP()
isUDP := conn.IsUDP()
networkType := conn.NetworkType()

// Protocol-specific operations
if tcpConn, ok := conn.AsTCPConn(); ok {
    tcpConn.SetKeepAlive(true)
}
3. TimeoutReader

Wrapper that adds timeout functionality to net.Conn:

reader := &conn.TimeoutReader{
    Conn:    netConn,
    Timeout: 30 * time.Second,
}

n, err := reader.Read(buffer)
4. DataExchange

Facilitates bidirectional data exchange between two connections:

// Exchange data between conn1 and conn2 with idle timeout
err := conn.DataExchange(conn1, conn2, 60*time.Second, buf1, buf2)

Supported Operations

TCP-Specific Operations
  • SetKeepAlive(bool) - Enable/disable keep-alive
  • SetKeepAlivePeriod(time.Duration) - Set keep-alive period
  • SetNoDelay(bool) - Enable/disable Nagle's algorithm
  • SetLinger(int) - Set linger time
  • CloseRead() - Close read side
  • CloseWrite() - Close write side
UDP-Specific Operations
  • ReadFromUDP([]byte) - Read UDP packet with sender address
  • WriteToUDP([]byte, *net.UDPAddr) - Send UDP packet to address
  • ReadMsgUDP([]byte, []byte) - Read UDP message with control data
  • WriteMsgUDP([]byte, []byte, *net.UDPAddr) - Send UDP message with control data
  • SetReadBuffer(int) - Set read buffer size
  • SetWriteBuffer(int) - Set write buffer size

Performance Benchmarks

The library has been extensively stress-tested under high-load conditions. Below are the performance test results:

High Concurrency Test
  • Concurrent Connections: 200
  • Operations per Connection: 20
  • Total Throughput: ~260-330 MB/s
  • Average Latency: ~12-16µs per operation
  • Total Data Transferred: ~15.6 MB (7.81 MB RX + 7.81 MB TX)
  • Test Duration: ~50-60ms
High Throughput Test
  • Concurrent Streams: 10
  • Data per Stream: 10 MB
  • Total Data: 100 MB
  • Throughput: ~350-620 MB/s (varies by system load)
  • Test Duration: ~320-570ms
Rate Limiter Performance
  • Concurrency: 20-50 goroutines
  • Operations: 500-1000 per goroutine
  • Token Bucket Algorithm: Efficient token distribution with minimal overhead
  • Thread Safety: Full atomic operations for concurrent access
Key Performance Characteristics
  • Low Latency: Sub-millisecond operation overhead
  • High Throughput: Capable of handling 600+ MB/s on modern hardware
  • Scalability: Tested with 200+ concurrent connections
  • Memory Efficiency: Minimal memory overhead with atomic operations
  • Thread Safety: Zero race conditions under high concurrency
Running Benchmarks

To run the stress tests yourself:

# Run all stress tests
go test -run TestStress -v -timeout 60s

# Run specific benchmark
go test -bench=BenchmarkStatConn -benchmem -benchtime=3s

# Run high concurrency test
go test -run TestStress_HighConcurrency -v

Note: Performance results may vary based on hardware, operating system, and system load. The above results were obtained on a Linux system with Go 1.25.4.

License

This project is licensed under the BSD 3-Clause License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Overview

Package conn 对 net.Conn 的扩展,包括超时读取、限速统计和双向数据交换等功能

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotTCPConn = errors.New("not a TCP connection")
	ErrNotUDPConn = errors.New("not a UDP connection")
)

定义错误

Functions

func DataExchange

func DataExchange(conn1, conn2 net.Conn, idleTimeout time.Duration, buffer1, buffer2 []byte) error

DataExchange 实现两个双向数据交换,支持空闲超时, 自定义缓冲区

Types

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter 全局令牌桶读写限速器

func NewRateLimiter

func NewRateLimiter(readBytesPerSecond, writeBytesPerSecond int64) *RateLimiter

NewRateLimiter 创建新的全局令牌桶读写限速器

func (*RateLimiter) Reset

func (rl *RateLimiter) Reset()

Reset 重置限速器状态

func (*RateLimiter) SetRate

func (rl *RateLimiter) SetRate(readBytesPerSecond, writeBytesPerSecond int64)

SetRate 动态调整读写速率

func (*RateLimiter) WaitRead

func (rl *RateLimiter) WaitRead(bytes int64)

WaitRead 等待读取令牌

func (*RateLimiter) WaitWrite

func (rl *RateLimiter) WaitWrite(bytes int64)

WaitWrite 等待写入令牌

type StatConn

type StatConn struct {
	Conn net.Conn
	RX   *uint64
	TX   *uint64
	Rate *RateLimiter
}

StatConn 是一个包装了 net.Conn 的结构体,用于统计并限制读取和写入的字节数

func NewStatConn

func NewStatConn(conn net.Conn, rx, tx *uint64, rate *RateLimiter) *StatConn

NewStatConn 创建一个新的 StatConn

func (*StatConn) AsTCPConn

func (sc *StatConn) AsTCPConn() (*net.TCPConn, bool)

AsTCPConn 安全地将底层连接转换为 *net.TCPConn

func (*StatConn) AsUDPConn

func (sc *StatConn) AsUDPConn() (*net.UDPConn, bool)

AsUDPConn 安全地将底层连接转换为 *net.UDPConn

func (*StatConn) Close

func (sc *StatConn) Close() error

Close 关闭连接

func (*StatConn) CloseRead

func (sc *StatConn) CloseRead() error

CloseRead 关闭TCP连接的读取端

func (*StatConn) CloseWrite

func (sc *StatConn) CloseWrite() error

CloseWrite 关闭TCP连接的写入端

func (*StatConn) GetConn

func (sc *StatConn) GetConn() net.Conn

GetConn 返回底层的 net.Conn

func (*StatConn) GetRX

func (sc *StatConn) GetRX() uint64

GetRX 返回已接收的字节数

func (*StatConn) GetRate

func (sc *StatConn) GetRate() *RateLimiter

GetRate 返回当前的限速

func (*StatConn) GetTX

func (sc *StatConn) GetTX() uint64

GetTX 返回已发送的字节数

func (*StatConn) GetTotal

func (sc *StatConn) GetTotal() uint64

GetTotal 返回总的传输字节数

func (*StatConn) IsTCP

func (sc *StatConn) IsTCP() bool

IsTCP 检查底层连接是否为TCP连接

func (*StatConn) IsUDP

func (sc *StatConn) IsUDP() bool

IsUDP 检查底层连接是否为UDP连接

func (*StatConn) LocalAddr

func (sc *StatConn) LocalAddr() net.Addr

LocalAddr 返回本地地址

func (*StatConn) NetworkType

func (sc *StatConn) NetworkType() string

NetworkType 返回底层连接的网络类型

func (*StatConn) Read

func (sc *StatConn) Read(b []byte) (int, error)

Read 实现了 io.Reader 接口,读取数据时会统计读取字节数并进行限速

func (*StatConn) ReadFromUDP

func (sc *StatConn) ReadFromUDP(b []byte) (int, *net.UDPAddr, error)

ReadFromUDP 从UDP连接读取数据包,返回数据和发送方地址

func (*StatConn) ReadMsgUDP

func (sc *StatConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)

ReadMsgUDP 从UDP连接读取消息,支持读取控制信息

func (*StatConn) RemoteAddr

func (sc *StatConn) RemoteAddr() net.Addr

RemoteAddr 返回远程地址

func (*StatConn) Reset

func (sc *StatConn) Reset()

Reset 重置统计数据

func (*StatConn) SetDeadline

func (sc *StatConn) SetDeadline(t time.Time) error

SetDeadline 设置连接的读写超时

func (*StatConn) SetKeepAlive

func (sc *StatConn) SetKeepAlive(keepalive bool) error

SetKeepAlive 设置TCP连接的KeepAlive状态

func (*StatConn) SetKeepAlivePeriod

func (sc *StatConn) SetKeepAlivePeriod(d time.Duration) error

SetKeepAlivePeriod 设置TCP连接的KeepAlive周期

func (*StatConn) SetLinger

func (sc *StatConn) SetLinger(sec int) error

SetLinger 设置TCP连接的Linger时间

func (*StatConn) SetNoDelay

func (sc *StatConn) SetNoDelay(noDelay bool) error

SetNoDelay 设置TCP连接的NoDelay状态(禁用/启用Nagle算法)

func (*StatConn) SetReadBuffer

func (sc *StatConn) SetReadBuffer(bytes int) error

SetReadBuffer 设置UDP连接的读取缓冲区大小

func (*StatConn) SetReadDeadline

func (sc *StatConn) SetReadDeadline(t time.Time) error

SetReadDeadline 设置连接的读取超时

func (*StatConn) SetWriteBuffer

func (sc *StatConn) SetWriteBuffer(bytes int) error

SetWriteBuffer 设置UDP连接的写入缓冲区大小

func (*StatConn) SetWriteDeadline

func (sc *StatConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline 设置连接的写入超时

func (*StatConn) Write

func (sc *StatConn) Write(b []byte) (int, error)

Write 实现了 io.Writer 接口,写入数据时会统计写入字节数并进行限速

func (*StatConn) WriteMsgUDP

func (sc *StatConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)

WriteMsgUDP 向UDP连接发送消息,支持发送控制信息

func (*StatConn) WriteToUDP

func (sc *StatConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error)

WriteToUDP 向指定UDP地址发送数据包

type TimeoutReader

type TimeoutReader struct {
	Conn    net.Conn
	Timeout time.Duration
}

TimeoutReader 包装了 net.Conn,支持设置读取超时

func (*TimeoutReader) Read

func (tr *TimeoutReader) Read(b []byte) (int, error)

Read 实现了 io.Reader 接口,读取数据时会设置读取超时

Jump to

Keyboard shortcuts

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