uio

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: Apache-2.0 Imports: 21 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

UIO - Ultra Fast I/O Framework for Go

GoDoc license-Apache 2

UIO (pronounced "ultra-IO") is a high-performance, event-driven networking framework for Go, designed for building scalable and efficient TCP/UDP servers and clients. It leverages modern I/O multiplexing techniques and provides a lightweight, non-blocking API for low-latency applications.

Features

  • 🚀 Event-Driven Architecture: Built on epoll/kqueue (Unix-like) for optimal I/O scheduling and stdio for others platform (Windows).
  • 🌐 Cross-Platform: Supports Linux, macOS, BSD variants, and Windows.
  • 🔄 Protocol Support: TCP, TCP4/TCP6, UDP, UDP4/UDP6, Unix domain sockets.
  • ⚡ Zero-Copy Optimizations: Batched read/write operations minimize memory copies.
  • 🧩 Flexible Event Hooks: OnOpen, OnData, OnClose callbacks for connection lifecycle management.
  • 🔧 Tunable Parameters:
    • Custom buffer sizes
    • Write buffering thresholds
    • Per-connection inbound/outbound limits
    • SO_REUSEPORT support

Installation

go get github.com/urpc/uio

Overview


type Events struct {
	// Pollers is set up to start the given number of event-loop goroutine.
	// The default value is runtime.NumCPU().
	Pollers int

	// ReusePort indicates whether to set up the SO_REUSEPORT socket option.
	// The default value is false.
	ReusePort bool

	// LockOSThread is used to determine whether each I/O event-loop is associated to an OS thread.
	// The default value is false.
	LockOSThread bool

	// MaxBufferSize is the maximum number of bytes that can be read from the remote when the readable event comes.
	// The default value is 4KB.
	MaxBufferSize int

	// WriteBufferedThreshold enabled when value is greater than 0, writes will go into the outbound buffer instead of attempting to send them out immediately,
	// unless the outbound buffer reaches the threshold or the flush function is manually called.
	//
	// If you have multiple Write call requirements, opening it will improve write performance because it reduces the number of system calls by merging multiple write operations to improve performance.
	// The default value is 0.
	WriteBufferedThreshold int

	// MaxOutboundBuffered limits accepted but unsent payload bytes per
	// connection. Zero disables the limit.
	MaxOutboundBuffered int

	// MaxPendingWrites limits write tasks that have not yet been consumed by
	// the connection's event loop. Values <= 0 use the default of 1024.
	MaxPendingWrites int

	// MaxInboundBuffered limits unread payload retained per connection. Zero
	// disables the limit.
	MaxInboundBuffered int

	// OnOpen fires when a new connection has been opened.
	OnOpen func(c Conn)

	// OnData fires when a socket receives data from the remote.
	OnData func(c Conn) error

	// OnClose fires when a connection has been closed.
	OnClose func(c Conn, err error)

	// OnInbound when any bytes read by a socket, it triggers the inbound event.
	OnInbound func(c Conn, readBytes int)

	// OnOutbound when any bytes write to a socket, it triggers the outbound event.
	OnOutbound func(c Conn, writeBytes int)

	// OnStart it triggers on the server initialized.
	OnStart func(ev *Events)

	// OnStop it triggers on the server closed.
	OnStop func(ev *Events)
}

Quick Start

Basic Echo Server

Events.Dial and Events.DialContext perform synchronous resolution and connection setup. Calls from callbacks currently running on an event loop return ErrDialOnEventLoop; start the call from an external goroutine instead. Use DialContext when the operation needs cancellation or a deadline. Events.Serve accepts zero or one listening address. Call Serve() without an address when using an Events instance only for outbound dialing.

Events.Adopt transfers an already-established stream connection into the event loops. The Events instance must already be serving, and ownership is consumed on both success and failure; the caller must never use the original net.Conn again after calling it.

Inside a connection callback, Conn.PeekChunk exposes the first contiguous inbound chunk without copying it. Process the returned slice before calling Discard; the slice is invalid after Discard or after the callback returns.

For encoders that can write into caller-provided storage, AcquireBuffer and Conn.WriteOwned avoid copying the encoded result into asynchronous outbound storage. WriteOwned consumes the buffer on both success and failure:

buffer := uio.AcquireBuffer(size)
dst := buffer.AvailableBuffer()[:size]
n, err := encode(dst)
if err != nil {
	uio.ReleaseBuffer(buffer)
	return err
}
buffer.CommitWrite(n)
_, err = conn.WriteOwned(buffer)
package main

import (
	"fmt"

	"github.com/urpc/uio"
)

func main() {

	var events uio.Events

	events.OnOpen = func(c uio.Conn) {
		fmt.Println("connection opened:", c.RemoteAddr())
	}

	events.OnData = func(c uio.Conn) error {
		_, err := c.WriteTo(c)
		return err
	}

	events.OnClose = func(c uio.Conn, err error) {
		fmt.Println("connection closed:", c.RemoteAddr())
	}

	if err := events.Serve(":9527"); nil != err {
		fmt.Println("server exited with error:", err)
	}
}

tcpkali2 Benchmark (2026-09-05)

The following results use tcpkali2 0.3.0 with 1,000 connections, a 3-second warmup, a 10-second measurement window, 1 KiB random messages, --pipeline, and the default TCP_NODELAY setting. Every run completed with a 100% success rate and zero connection errors. The UWS server used here has compression disabled. P99 is saturated pipeline latency, not idle single-request latency.

Plain TCP was run with:

tcpkali2 -c 1000 --connect-rate 2000 -T 10s --warmup 3s \
  -s 1024 --pipeline 127.0.0.1:9527

The UWS run adds --websocket and targets port 19701.

OS Service Backend Requests/s Avg latency P99 latency Bandwidth
macOS M4 Pro UIO TCP echo events 1,060,782 30.22 ms 106.05 ms 2,172 MB/s
macOS M4 Pro UIO TCP echo stdio 2,279,489 13.07 ms 22.69 ms 4,668 MB/s
macOS M4 Pro UWS echo events 651,341 48.61 ms 479.49 ms 1,334 MB/s
macOS M4 Pro UWS echo stdio 2,020,297 14.09 ms 27.57 ms 4,138 MB/s
Linux Xeon, 48 logical CPUs UIO TCP echo events 3,726,609 5.77 ms 12.19 ms 7,632 MB/s
Linux Xeon, 48 logical CPUs UIO TCP echo stdio 3,370,873 6.37 ms 13.62 ms 6,904 MB/s
Linux Xeon, 48 logical CPUs UWS echo events 946,234 32.60 ms 81.66 ms 1,938 MB/s
Linux Xeon, 48 logical CPUs UWS echo stdio 2,004,953 10.69 ms 22.32 ms 4,106 MB/s

Linux peak RSS sampled during the same runs was approximately 10 MiB for UIO events, 62 MiB for UIO stdio, 13 MiB for UWS events, and 66 MiB for UWS stdio. The difference comes from stdio's per-connection read/write goroutines and buffers; it is expected to grow with the number of live connections.

Selection guidance
  • For UWS or high-throughput RPC with a moderate number of active connections, stdio is currently the faster path and has substantially lower saturated P99.
  • For plain UIO TCP echo on the tested Linux host, events is about 11% faster and uses much less memory. It is the better choice when connection count is the primary constraint.
  • For large numbers of long-lived connections, prefer events even when stdio wins throughput: its memory footprint is shared by event loops instead of being proportional to two goroutines and a read buffer per connection.
  • Results are platform and workload dependent. Linux and macOS use different pollers and CPU/NUMA topologies, and pipeline saturation amplifies queueing latency. Use the same connection count, payload, Go version, CPU placement, and warmup when comparing a deployment.

License

The repository released under version 2.0 of the Apache License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrOutboundOverflow       = errors.New("uio: outbound buffer limit exceeded")
	ErrInboundOverflow        = errors.New("uio: inbound buffer limit exceeded")
	ErrTaskQueueFull          = errors.New("uio: pending write task limit exceeded")
	ErrUnflushedData          = errors.New("uio: connection closed with unflushed data")
	ErrDialOnEventLoop        = errors.New("uio: Dial cannot run on an event loop")
	ErrTooManyListenAddresses = errors.New("uio: Serve accepts at most one listen address")
)

Functions

func ReleaseBuffer added in v1.1.0

func ReleaseBuffer(buffer *Buffer)

ReleaseBuffer returns an unsubmitted buffer to the pool. It must be called at most once, and the buffer must not be used afterward.

Types

type Buffer added in v1.1.0

type Buffer = bytebuf.Buffer

Buffer is reusable byte storage that can be transferred to a connection with Conn.WriteOwned. Newly acquired writable capacity is not zeroed; every committed byte must be initialized. A Buffer must not be used after its ownership is transferred or it is released.

func AcquireBuffer added in v1.1.0

func AcquireBuffer(capacity int) *Buffer

AcquireBuffer returns an empty pooled buffer with at least capacity bytes of writable space. Release it when ownership is not transferred to WriteOwned.

type CompositeBuffer

type CompositeBuffer = bytebuf.CompositeBuffer

type Conn

type Conn interface {
	// LocalAddr is the connection's local socket address.
	LocalAddr() net.Addr

	// RemoteAddr is the connection's remote address.
	RemoteAddr() net.Addr

	// Userdata returns user-defined connection data. It may be called outside a
	// callback, but callers must serialize it with SetUserdata.
	Userdata() any

	// SetUserdata replaces user-defined connection data. It may be called outside
	// a callback, but callers must serialize it with Userdata.
	SetUserdata(value any)

	// SetLinger sets the behavior of Close on a connection which still
	// has data waiting to be sent or to be acknowledged.
	//
	// If sec < 0 (the default), the operating system finishes sending the
	// data in the background.
	//
	// If sec == 0, the operating system discards any unsent or
	// unacknowledged data.
	//
	// If sec > 0, the data is sent in the background as with sec < 0. On
	// some operating systems after sec seconds have elapsed any remaining
	// unsent data may be discarded.
	SetLinger(secs int) error

	// SetNoDelay controls whether the operating system should delay
	// packet transmission in hopes of sending fewer packets (Nagle's
	// algorithm).
	// The default is true (no delay), meaning that data is sent as soon as possible after a Write.
	SetNoDelay(nodelay bool) error

	// SetKeepAlive sets whether the operating system should send
	// keep-alive messages on the connection.
	SetKeepAlive(keepalive bool) error

	// SetKeepAlivePeriod tells operating system to send keep-alive messages on the connection
	// and sets period between TCP keep-alive probes.
	SetKeepAlivePeriod(secs int) error

	// SetReadBuffer sets the size of the operating system's
	// receive buffer associated with the connection.
	SetReadBuffer(size int) error

	// SetWriteBuffer sets the size of the operating system's
	// transmit buffer associated with the connection.
	SetWriteBuffer(size int) error

	// SetDeadline sets deadline for both read and write.
	// If it is time.Zero, SetDeadline will clear the deadlines.
	SetDeadline(t time.Time) error

	// SetReadDeadline sets the deadline for future Read calls.
	// When the user doesn't update the deadline and the deadline exceeds,
	// the connection will be closed.
	// If it is time.Zero, SetReadDeadline will clear the deadline.
	SetReadDeadline(t time.Time) error

	// SetWriteDeadline sets the deadline for future data writing.
	// If it is time.Zero, SetWriteDeadline will clear the deadline.
	SetWriteDeadline(t time.Time) error

	// Peek returns the next len(b) bytes without advancing the inbound buffer.
	// It may only be called from a connection callback.
	Peek(b []byte) []byte

	// PeekChunk returns the first contiguous inbound chunk without advancing it.
	// The returned slice is valid only until Discard or the callback returns.
	// It may only be called from a connection callback.
	PeekChunk() []byte

	// Discard advances the inbound buffer with next n bytes, returning the number of bytes discarded.
	// It may only be called from a connection callback.
	Discard(n int) (int, error)

	// InboundBuffered returns a inbound buffer data length.
	// It may only be called from a connection callback.
	InboundBuffered() int

	// OutboundBuffered returns accepted payload bytes not yet sent, including
	// both queued write tasks and the loop-owned outbound buffer.
	OutboundBuffered() int

	// WriterTo
	// It may only be called from a connection callback.
	// Notice: non-blocking interface, should not be used as you use std.
	io.WriterTo

	// ReadWriteCloser
	// Read may only be called from a connection callback. Write and Close are
	// safe from other goroutines.
	// Notice: non-blocking interface, should not be used as you use std.
	io.ReadWriteCloser

	// ByteWriter
	// Notice: non-blocking interface, should not be used as you use std.
	io.ByteWriter

	// StringWriter
	// Notice: non-blocking interface, should not be used as you use std.
	io.StringWriter

	// Writev "writev"-like batch write optimization.
	// Notice: non-blocking interface, should not be used as you use std.
	Writev(vec [][]byte) (int, error)

	// WriteOwned submits buffer without copying and always consumes its
	// ownership, including when it returns an error. For UDP, one buffer is sent
	// as one datagram.
	WriteOwned(buffer *Buffer) (int, error)

	// Flush schedules buffered data for writing without waiting for socket I/O.
	// Writes accepted before Flush remain ordered before later writes.
	Flush() error

	// Wake schedules one OnData callback after previously submitted tasks.
	Wake() error

	// CloseWith asynchronously closes the connection on its owning loop.
	// On Unix, unsent accepted payload is reported as UnflushedError.
	CloseWith(err error) error
}

Conn is a non-blocking connection managed by an event loop. On Unix, callbacks and connection state run on the owning loop. Writes from other goroutines are safe and retain no caller-owned data after returning. Close and CloseWith return after the close request is accepted; OnClose is final.

type Events

type Events struct {

	// Pollers is set up to start the given number of event-loop goroutine.
	// The default value is runtime.NumCPU().
	Pollers int

	// ReusePort indicates whether to set up the SO_REUSEPORT socket option.
	// The default value is false.
	ReusePort bool

	// LockOSThread is used to determine whether each I/O event-loop is associated to an OS thread.
	// The default value is false.
	LockOSThread bool

	// MaxBufferSize is the maximum number of bytes that can be read from the remote when the readable event comes.
	// The default value is 4KB.
	MaxBufferSize int

	// WriteBufferedThreshold enabled when value is greater than 0, writes will go into the outbound buffer instead of attempting to send them out immediately,
	// unless the outbound buffer reaches the threshold or the flush function is manually called.
	//
	// If you have multiple Write call requirements, opening it will improve write performance because it reduces the number of system calls by merging multiple write operations to improve performance.
	// The default value is 0.
	WriteBufferedThreshold int

	// MaxOutboundBuffered limits accepted but unsent payload bytes per
	// connection. Zero disables the byte limit.
	MaxOutboundBuffered int

	// MaxPendingWrites limits write tasks not yet consumed by a connection's
	// event loop. Values <= 0 use a default of 1024.
	MaxPendingWrites int

	// MaxInboundBuffered limits unread payload retained per connection. Zero
	// disables the limit.
	MaxInboundBuffered int

	// OnOpen fires when a new connection has been opened.
	OnOpen func(c Conn)

	// OnData fires when a socket receives data from the remote.
	OnData func(c Conn) error

	// OnClose fires when a connection has been closed.
	OnClose func(c Conn, err error)

	// OnInbound when any bytes read by a socket, it triggers the inbound event.
	OnInbound func(c Conn, readBytes int)

	// OnOutbound when any bytes write to a socket, it triggers the outbound event.
	OnOutbound func(c Conn, writeBytes int)

	// OnStart it triggers on the server initialized.
	OnStart func(ev *Events)

	// OnStop it triggers on the server closed.
	OnStop func(ev *Events)
	// contains filtered or unexported fields
}

func (*Events) Adopt added in v1.1.0

func (ev *Events) Adopt(conn net.Conn, userdata any) (Conn, error)

Adopt transfers ownership of an established stream connection to ev. The caller must not use conn after calling Adopt, including when Adopt returns an error. ev must already be serving.

func (*Events) Close

func (ev *Events) Close(err error) error

func (*Events) Dial

func (ev *Events) Dial(addr string, userdata any) (Conn, error)

Dial connects to the address on the named network.

Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and "unixpacket".

Examples:

Dial("tcp://golang.org:http")
Dial("tcp://192.0.2.1:http")
Dial("tcp://198.51.100.1:80")
Dial("udp://[2001:db8::1]:domain")
Dial("udp://[fe80::1%lo0]:53")
Dial("tcp://:80")
Dial("unix:///path/your/unix.sock")

func (*Events) DialContext added in v1.0.1

func (ev *Events) DialContext(dialCtx context.Context, addr string, userdata any) (Conn, error)

DialContext connects from outside event callbacks and allows cancellation while resolving or establishing the network connection.

func (*Events) Serve

func (ev *Events) Serve(addrs ...string) (err error)

Serve starts the event loops and optionally listens on one address. Calling Serve without an address starts a dial-only Events. More than one address is rejected.

type UnflushedError added in v1.1.0

type UnflushedError struct {
	Remaining int64
}

UnflushedError reports payload accepted by the framework but not sent before the connection was closed.

func (UnflushedError) Error added in v1.1.0

func (err UnflushedError) Error() string

func (UnflushedError) Unwrap added in v1.1.0

func (err UnflushedError) Unwrap() error

Directories

Path Synopsis
examples module
internal
taskqueue
Package taskqueue provides a small intrusive MPSC FIFO queue.
Package taskqueue provides a small intrusive MPSC FIFO queue.
uws
Package uws provides an asynchronous WebSocket server built on UIO.
Package uws provides an asynchronous WebSocket server built on UIO.
autobahn/server command
examples/echo command
internal/frame
Package frame implements the wire-level WebSocket frame codec.
Package frame implements the wire-level WebSocket frame codec.

Jump to

Keyboard shortcuts

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