Skip to content
urpcPublic

About

uio is a ultra-fast, lightweight, non-blocking, event-driven networking framework written in pure Go

Topics

Resources

Stars

23 stars

Watchers

1 watching

Forks

Latest commit

 

History

293 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

uio: event-driven networking for Go

Go Reference CI License

uio is an event-driven networking library for Go. You write a few callbacks; uio watches the sockets, runs your code when a connection has something to say, and sends your replies in as few system calls as it can — without a goroutine per connection.

Highlights

  • Callbacks, not goroutines. OnOpen, OnRead, OnTimer and OnClose run in order for each connection and never overlap, so the state they share needs no locks, and on epoll/kqueue an idle connection is a small struct rather than a parked goroutine.
  • A slow handler stalls nothing else. On epoll/kqueue, event loops only collect readiness; callbacks run on a worker pool, and work stuck behind a blocked callback is handed to another worker within milliseconds.
  • Write from anywhere. Write, WriteOwned and Close are safe from any goroutine; bytes leave in the order they were written.
  • Zero-copy where it counts. Decode packets straight from the read buffer, encode replies straight into the send queue, and send a round of replies together, usually in one writev.
  • Built-in backpressure. Per-connection limits on buffered input and output: input past its limit pauses reads, so TCP flow control slows a flooding peer, and output past its limit fails the write instead of growing memory without bound.
  • Cross-platform. epoll on Linux, kqueue on macOS and the BSDs, and a portable goroutine-per-connection backend on Windows (or anywhere with -tags stdio).
  • TCP, UDP and Unix sockets, listening and dialing, IPv4 and IPv6.

Install

go get github.com/urpc/uio

uio needs Go 1.25 or newer.

Quick start

An echo server:

package main

import (
	"log"

	"github.com/urpc/uio"
)

func main() {
	events := &uio.Events{
		Handler: uio.FuncHandler{
			Open: func(c uio.Conn) {
				log.Println("hello", c.RemoteAddr())
			},
			Read: func(c uio.Conn) error {
				_, err := c.WriteTo(c) // echo everything that arrived
				return err
			},
			Close: func(c uio.Conn, err error) {
				log.Println("bye", c.RemoteAddr(), err)
			},
		},
	}

	log.Fatal(events.Serve(":9527"))
}

Serve accepts several addresses at once, with an optional scheme: ":9527", "tcp6://[::1]:9527", "udp://:5353", "unix:///tmp/app.sock". Once Serve is running (Serve() with no address for a dial-only client), the same Events can dial out with Dial or DialContext, take over an established stream net.Conn with Adopt, or add an address with Listen(addr, opts...). Each connection a listener accepts starts with the Userdata its WithUserdata option names, and closing the returned Listener stops accepting there while the connections it accepted stay open (a UDP listener's peers share its socket and close with it). A packet listener also dials: assert the returned Listener to a PacketListener and DialPeer(raddr, userdata) makes the peer's connection on the listener's own socket — what it sends leaves from the listener's address and the peer's answers reach that connection, as they would had the peer spoken first — which is the entry point for hole punching; WriteTo sends a single datagram the same way.

For OS socket options (SetNoDelay, SetKeepAlive, SetLinger, buffer sizes) and raw descriptor access, uio.SocketOf(c) returns the underlying SocketConn, and SocketConn.Control(fn) runs fn with the connection's descriptor — IP_TTL for a NAT probe, IP_TOS, SO_MARK — while the SocketControl options run before a socket connects or binds: WithDialControl on a dial, WithLocalAddr binds the dial's socket first, and WithListenControl runs on a Listen's socket before it binds. fd is valid only for the call, and these are the hooks a hole punch needs; the punching itself is yours.

How it works

Event loops collect readiness, a sharded scheduler keeps each connection's turns serialized on one shard, a connection turn reads and runs your callbacks, and a write turn sends writes from other goroutines

  1. Watch. A few event loops — epoll or kqueue instances, one per four Ps by default — accept connections and collect readiness. They never run your code.
  2. Queue. A ready connection is handed to a sharded worker pool. Its turns go to the shard its key picks — the pool adds shards as connections grow — so its work tends to return to the same CPU, where its socket is still warm in cache. You can supply your own scheduler through Events.Executor.
  3. Serve. A connection's turn reads the socket, runs OnRead, and then flushes every reply the callback wrote in one go. Turns of one connection never overlap; different connections run in parallel.

A write from another goroutine — say, an RPC reply that finishes later — is queued and sent by a short write turn, so it does not wait for a slow read. Only one sender touches a socket at a time, and bytes leave in the order they were written.

Timed turns. SetWakeDeadline schedules an OnTimer for a connection at a time of your choosing, within one scheduler tick of it — for heartbeats, protocol update ticks and idle timeouts; SetWakeInterval repeats it every period. The timer turn runs OnTimer and then OnRead, which may find bytes already buffered; due is computed against the clock, so a wake or a read that arrives first runs the timer just the same, once. On the native backend the timers live on a per-loop timing wheel that a kernel timer wakes, so an armed timer costs no goroutine and an idle connection none at all; the stdio backend runs one runtime timer per armed connection.

This describes the native epoll/kqueue backend. The portable stdio backend used on Windows (or with -tags stdio) gives each stream connection its own reader and writer goroutines instead.

Protocol layers

A protocol that is not yours to implement — TLS, compression, an auth handshake — can sit between the socket and your handler as a protocol layer. WithLayers names a chain on an endpoint — a Listen, a dial, an adoption — and UIO stacks it under Events.Handler; the first layer in it sits nearest the wire. A Listener carries its one chain for its life; a Dialer may hold defaults each dial overrides.

A wss server is the smallest complete example: a TLS layer, a WebSocket package, and one line joining them. The two directions run through the same stack and mirror each other exactly.

Reading, left to right: the socket hands up TLS records, the TLS layer decrypts them into a plaintext stream, the WebSocket protocol deframes that stream into messages, and your handler sees payloads.

Writing, right to left: SendText becomes a frame, the frame is encrypted into a TLS record, and the record leaves by the same socket.

Two rows over the same four boxes — socket, tls, websocket, handler: the top row reads left to right, decrypting then deframing into messages, and the bottom row writes right to left, framing then encrypting

The same seam carries a datagram transport into the model. ukcp runs KCP — a reliable stream over an unreliable datagram network — as a PacketLayer: on a UDP connection it reads a datagram per turn and hands the layers above a reliable stream, so TLS composes over it exactly as it does over TCP. Above a stream it frames its segments itself, so another KCP or a TLS connection composes below it just as well:

listener, err := events.Listen("udp://:9000",
	uio.WithLayers(ukcp.ServerLayer(ukcp.LayerOptions{}),
		utls.ServerLayer(utls.LayerOptions{TLSConfig: cfg})))
// the Handler reads a TLS stream carried by KCP over UDP

A layer transforms bytes, and UIO carries everything else. Writing one means writing what the protocol changes — nothing more:

type Layer interface {
	Attach(ctx LayerContext) LayerHandler // once per connection
}

type LayerHandler interface {
	OnOpen(ctx LayerContext)                            // start a handshake; ctx.Open() when settled
	OnRead(ctx LayerContext) error                      // a turn: read Lower(), write Upper()
	OnWrite(ctx LayerContext, p []byte) (int, error)    // bytes from above → ctx.Lower().Write(...)
	OnTimer(ctx LayerContext) error                     // this layer's own timer came due
	OnClose(ctx LayerContext, cause error)
}

Layer is the protocol, configured once; LayerHandler is its instance on one connection; LayerContext is that instance's place in the stack: Lower(), the connection below it reads from, Upper(), the layer above's input it writes to, and the connection's lifecycle — ctx.Close() says this layer's goodbye and drains the queue like a close from above, ctx.Abort(cause) ends it at once. Lower() carries bytes, options and addressing, never a close: a layer ends the connection through the context, so every close runs the stack's one close algorithm from the layer that began it (CloseWrite stays: ending one direction is part of a layer's own protocol). An obfuscation layer is all of this:

type xorHandler struct {
	uio.PassThrough // open at once, pass through what is not overridden
	key byte
}

func (x *xorHandler) OnRead(ctx uio.LayerContext) error {
	in := ctx.Lower().PeekChunk()
	_, _ = ctx.Upper().Write(xor(in, x.key))
	_, err := ctx.Lower().Discard(len(in))
	return err
}

func (x *xorHandler) OnWrite(ctx uio.LayerContext, p []byte) (int, error) {
	if _, err := ctx.Lower().Write(xor(p, x.key)); err != nil {
		return 0, err
	}
	return len(p), nil
}

ln, err := events.Listen(addr, uio.WithLayers(
	uio.LayerFunc(func(uio.LayerContext) uio.LayerHandler { return &xorHandler{key: 0x5a} }),
))

examples/xorlayer runs this layer for real, on both ends of one connection, under a second layer that prints the bytes on the wire: go run ./xorlayer in examples shows a message leave as plaintext, cross the wire XOR'd, and arrive as plaintext again.

The layer above — the next layer or your Handler — gets a Conn UIO builds over this one: its reads are what the layer delivered, its writes reach OnWrite, its addresses, userdata, and deadlines are the connection's own, and uio.SocketOf(conn) reaches the underlying OS socket options. A layer writes none of that.

One connection through the stack

Every endpoint names its own chain. A Listener carries the one a Listen gave it, fixed for its life: one port, one stack. A Dialer holds the defaults it was built with — events.Dialer(uio.WithLayers(tls)) — and each dial may name its own, replacing them for that connection alone: one Dialer serves wss:// and ws:// alike, the first dial naming the TLS layer and the second WithLayers(PassThroughLayer). DialContext(ctx, addr, uio.WithLayers(tls)) on the Events is the chainless default Dialer naming the chain for that one dial.

uio.WithLayers(kcp, tls, trace) creates one LayerHandler for each connection of that endpoint. The first layer named is closest to the wire; the Handler sees the top layer. The whole path is:

build + open (once per connection)

connection
   │
   ├─ stackDriver.OnOpen
   ├─ Attach(kcp) → Attach(tls) → Attach(trace)
   └─ kcp.OnOpen ─ctx.Open()→ tls.OnOpen ─ctx.Open()→ trace.OnOpen
      ─ctx.Open()→ Handler.OnOpen   (each opens after the one below
      returned — never inside another callback — and the dial settles
      once the Handler's OnOpen returned)

one turn: inbound goes up, outbound goes down

inbound  socket ──► [kcp] ──► [tls] ──► [trace] ──► Handler.OnRead
                    Lower().Read Upper().Write Upper().Write Conn.Read

outbound socket ◄── [kcp] ◄── [tls] ◄── [trace] ◄── Handler.Conn.Write
                    Lower().Write Lower().Write Lower().Write

close

Handler calls Close, or a layer ctx.Close/Abort (walked on a turn)
   └─ closing published once; the close passes downward, OnClosing frames
      queued first on a graceful close ──► the socket drains, then closes
      └─ Handler.OnClose → trace.OnClose → tls.OnClose → kcp.OnClose

Every layer reads the connection ctx.Lower() and writes the layer above's input ctx.Upper(): Read and Write, the same verbs at every level, up to the Handler's own Conn. A write from above arrives as OnWrite, transforms, and leaves through Lower().Write. A due layer timer runs before that layer's OnRead.

What UIO guarantees every layer

These are UIO's to keep, not each layer's to remember:

  1. Every turn reaches the layers above, whether or not a layer delivered anything. A wake, or a timer armed higher up, reaches the Handler through any stack — a layer cannot swallow it.
  2. Every layer has a timer of its own. LayerContext.SetTimer and LayerContext.SetTimerInterval arm the layer's timer, and the Handler's SetWakeDeadline is a slot of its own too: no layer replaces another's.
  3. The turn callbacks never overlap. OnOpen, OnRead, OnTimer, OnClosing, OnClose and the Handler's callbacks run on the connection's turns, whatever asked for the close. The others run where they are called for and may overlap the turns: OnWrite on the writer's goroutine, CloseWrite on the goroutine closing the connection or on the turn that finishes its end, and OutboundHeld on writers'. State they share needs a lock. UIO never calls a layer from below or from inside another layer's callback — ctx.Open() records a request, and the layers above open on the turn's open stage, after the calling callback returned — so a layer may hold its lock while it writes or closes below.
  4. A connection ends once, top down. The Handler's OnClose comes first, if its OnOpen ran, then every layer's. A connection whose stack never opened — a failed handshake — ends without a Handler callback. Once a close has begun — from the Handler or from any layer — no new call reaches a layer from a turn: writes and flushes return net.ErrClosed, and only OnClose follows. A repeated Close reports net.ErrClosed (or yields when called via ctx.Close), while Abort cuts any graceful drain short at once — and no second close walk starts. The close itself is the one caller left: the OnClosing hooks it walks below the layer that began it.
  5. The end of a stream travels up. A layer whose peer ended its stream calls ctx.Upper().End(); the layer above reads io.EOF after the rest. At the top it closes the connection, or, with AllowHalfOpen, leaves the Handler to end its own half with CloseWrite.
  6. MaxOutboundBuffered refuses whole writes, at the top. The Handler's write is checked against the queue below it before it enters the stack, and reserves its room, so concurrent writers cannot pass the limit together; what a layer writes below is never refused — a TLS record, once encrypted, has to reach the wire.
  7. A graceful close lets the queue leave first. Close on a connection closes the socket once what was queued — the layers' OnClosing frames included — has left, or once it stopped moving for uio.LingerTimeout; what arrives meanwhile is discarded. Abort and ctx.Abort end it at once. A layer closing the connection itself does so through ctx.Close() or ctx.Abort(cause): the same one close algorithm, begun at that layer.
  8. MaxInboundBuffered covers the whole stack. Bytes the layers hold for the Handler count against it with the socket's buffer: a stack holding the limit takes nothing more from the socket until the Handler reads.
  9. Layers carry streams. A packet connection — UDP, IP, unixgram, unixpacket — takes a PacketLayer at the bottom of the chain (ukcp runs KCP as one): that layer reads the datagrams and hands the layers above the stream it makes of them. A chain without one is refused with ErrLayersNeedStream.

A layer carries one connection: one above for each one below. A protocol that opens several streams over one connection — HTTP/2, QUIC — is the Handler's to model, over a connection the layer below it made.

Dials and adopted connections run the same stack

DialContext returns only once the whole stack has opened, and the Conn it returns is the top layer's — encrypted underneath, plaintext to you. Adopt and AdoptContext do the same for a net.Conn you hand over:

client := &uio.Events{}
conn, err := client.DialContext(ctx, "tcp://example.org:443",
	uio.WithLayers(utls.ClientLayer(utls.LayerOptions{TLSConfig: cfg})))
// conn reads and writes plaintext; utls encrypts below it

A layer that fails before the stack opens reports its error from DialContext, and the Handler hears nothing of the connection — no OnOpen, no OnClose. What a layer negotiated is its own to report: uio.FindLayer[T](conn) returns the first layer of type T at or below conn — uio.FindLayer[interface{ State() tls.ConnectionState }](conn) finds the TLS state under any stack — and uio.LayerOf(conn) the one that built conn.

A LayerHandler may also implement optional interfaces:

  • CloseWriter ends one direction in its own protocol (a TLS close_notify). A layer without it does not support CloseWrite — embedding PassThrough does not grant it (PassThroughLayer does, as the layer that changes nothing). UIO calls it only after what was written before CloseWrite has gone below: writes in flight finished and held output sent.
  • LayerCloser sends a protocol close frame (OnClosing) as the connection closes, told the close's cause.
  • OutboundHolder is for a layer that holds output of its own, such as a send window: what it holds counts in OutboundBuffered and MaxOutboundBuffered.

Conn.State() reports where the streams stand — StateReadEnded, StateWriteEnded, StateClosing, StateClosed — read on the connection's turn, replacing the old probe reads.

What it is not

  • Not request middleware. A layer runs once per connection and transforms its byte stream; it never sees a request or a message. Per-message work belongs in OnRead.
  • Observer and Hooks do not run through layers. They count the bytes on the wire, which is what makes them right for traffic accounting; the connection they are told about is the one your Handler holds. They only observe: OnBytesWritten may run inside a layer's write, so it must not write to or close the connection.
  • A chain belongs to an endpoint, not to the Events. A Listen names its chain when the listener is created and keeps it for its life; a dial names one, or takes its Dialer's defaults. An endpoint that names no chain runs plain.
  • The stack is fixed once a connection starts. There is no runtime layer replacement — a protocol that sniffs its first bytes (ALPN, a PROXY header) decides inside one layer, not by trading the stack.
  • Packet connections need a PacketLayer at the bottom. UDP, IP and unixgram/unixpacket are refused with ErrLayersNeedStream unless the first layer of the chain declares it takes packets (CarriesPackets): that layer reads one datagram per turn and hands the layers above a stream — ukcp runs KCP exactly this way. It is never paced; a datagram it does not take is gone, so its own protocol carries the backpressure.
  • A layer's delivery to the layer above is paced (DefaultDeliverBound, or MaxInboundBuffered): the framework stops calling a layer whose delivery is full until the layer above reads. The bound is a pacing threshold, not a cap on one write: the write that crosses it — and any a layer makes from OnOpen — lands whole. A Handler that peeks a whole frame without consuming (ReserveInbound + PeekChunk) therefore sees about one bound's worth from a layer that delivers in chunks; set MaxInboundBuffered to size such frames.

Configuration

Everything is optional; the zero Events is ready to use.

Field Default What it does
Pollers one per 4 Ps: 1–8 native, at least 2 on stdio Number of event loops, never more than GOMAXPROCS.
Executor built-in sharded pool Your own scheduler for connection and write turns (native backend).
ReadBufferSize 4 KiB Bytes read per socket read.
WriteBufferedThreshold off Native backend: callback writes smaller than this are queued for the end of the turn instead of sent at once. Replies written in OnRead are batched either way.
MaxOutboundBuffered off Per-connection limit on unsent bytes; a write past it returns ErrOutboundOverflow (unless BlockingWrite suspends off-turn callers).
BlockingWrite off Suspends off-turn stream Write/Writev/WriteOwned/SendFile callers when the outbound window is full instead of returning ErrOutboundOverflow (defaults an unset MaxOutboundBuffered to 64 KiB; on-turn callbacks stay non-blocking). NewBlockingConn/NewBlockingReader/NewBlockingWriter offer explicit pull/blocking wrappers.
MaxInboundBuffered off Per-connection limit on read but not yet consumed bytes. Once callbacks leave this much unconsumed, the connection stops reading its socket and TCP flow control slows the peer; a Wake whose OnRead consumes below the limit reads on. A ReserveInbound larger than the limit returns ErrInboundOverflow. A packet connection keeps no buffer to hold and is never paced by it: its bottom PacketLayer carries whatever backpressure its protocol provides.
AllowHalfOpen off Keeps a stream connection open after the peer shuts its writing half: OnRead runs once more, Read reports io.EOF once the buffered bytes are consumed, and the connection can still write until CloseWrite shuts this side's half too; it closes once both halves are shut and the bytes the peer sent have been consumed.
ReusePort off Sets SO_REUSEPORT on listeners.
LockOSThread off Locks each event-loop goroutine to its own OS thread; callback workers are unaffected.

The callbacks are three interfaces, each its own field of Events:

Field Interface Methods
Handler Handler OnOpen, OnRead, OnTimer, OnClose: every connection's lifecycle, data and timers
Observer TrafficObserver OnBytesRead, OnBytesWritten: bytes read and written
Hooks ServeHooks OnStart, OnStop: around Serve

Any type implementing an interface fits its field. FuncHandler adapts plain functions to all three: set it as whichever fields its functions fill, and leave the rest unset. An unset field, or a nil FuncHandler function, costs nothing; the three are read once, when Serve starts.

Backpressure

When a connection's data goes somewhere slower — a peer it forwards to, an upstream call, a work queue — stop its input once that destination is behind, and release it when the destination has room again. PauseRead and ResumeRead are that switch:

relay := uio.FuncHandler{
	Read: func(c uio.Conn) error {
		peer := peerOf(c) // the destination this connection forwards to
		if peer.OutboundBuffered() >= high {
			_ = c.PauseRead() // the destination is behind: stop the source
		}
		_, err := c.WriteTo(peer)
		return err
	},
}
// The destination drained: let the source's input through again.
relay.BytesWritten = func(dest uio.Conn, _ int) {
	if dest.OutboundBuffered() <= low {
		_ = sourceOf(dest).ResumeRead()
	}
}

While a plain stream is paused its socket is not read, so TCP flow control slows the peer at once and what was already read stays in the connection: ResumeRead schedules the turn that hands it to OnRead, and a write past the destination's own MaxOutboundBuffered fails with ErrOutboundOverflow, so the pause above keeps memory bounded without closing anyone. Pausing keeps timers, writes and close work running; it never releases another owner's pause (protocol layers and helpers hold pauses of their own), and it is safe from any goroutine. A full Wake-based variant of the same loop — leave the bytes unconsumed until MaxInboundBuffered stops the socket, then Wake the source when the destination drains — needs no API beyond OutboundBuffered.

PauseRead is the application's one switch, idempotent rather than reference counted. What was read is kept and handed to the first OnRead after ResumeRead, and the peer's end of the stream waits behind it: a paused connection does not close for its peer's end until it resumed and saw what it kept. A reset, a fatal error or a local close ends it regardless (on the portable stdio backend a reset behind a pause is seen once reading resumes or a read deadline passes: the socket is not read while paused). A layered stack keeps reading its socket into its bounds (MaxInboundBuffered, or 64 KiB when that is zero) while its Handler is paused. A callback or socket read already in flight finishes, so a protocol handling several messages in one callback checks ReadPaused() between them. Raw datagram connections report ErrUnsupported: their peers share a socket.

ubridge.Bridge is this loop packaged for one shape: a relay whose every accepted connection is dialed to one upstream. A leg whose destination queue reaches InboundLimit (256 KiB by default) leaves its input unconsumed, forwards again once the queue drains to half, and splits a read larger than the destination's write budget:

bridge := &ubridge.Bridge{Upstream: "tcp://127.0.0.1:9527"}
events := bridge.Events()
err := events.Serve("tcp://:9528")

For anything else — many destinations per source, a choice of upstream per connection, a store between the sides — drive the pause yourself, as above.

Going faster

These are optional. Plain Read, Write and WriteTo work on every backend.

Read a TLS record whole. A TLS record carries up to 16 KiB, and crypto/tls reads a record per socket read: the default 4 KiB ReadBufferSize splits every record across four rounds, and each round carries its ciphertext through the stack again. At 16 KiB — the record size, the socket-read cadence the standard library runs at — a TLS layer moves about 1.4× the bytes of the 4 KiB default and ahead of crypto/tls on the same wire; at 64 KiB, four records per read, 1.4–1.8× the default across the hosts we ran, the fastest point on both. Smaller frames lose nothing to the bigger reads: ReserveInbound and PeekChunk read a frame from wherever in the buffer it lies.

Decode in place. PeekChunk returns the first chunk of buffered bytes without copying. For a length-prefixed protocol, ReserveInbound gathers a packet that spans several reads into one chunk, so it can still be decoded in place:

func onRead(c uio.Conn) error { // a Handler's OnRead, or a FuncHandler's Read
	var header [4]byte
	for {
		h := c.Peek(header[:]) // copies only if the header spans reads
		if len(h) < 4 {
			return nil // wait for the header
		}
		size := binary.BigEndian.Uint32(h)
		if size > maxPacket {
			return errTooBig // check before reserving: it allocates
		}
		total := 4 + int(size)
		if err := c.ReserveInbound(total); err != nil {
			return err
		}
		chunk := c.PeekChunk()
		if len(chunk) < total {
			return nil // the rest is on its way
		}
		handle(chunk[4:total])
		c.Discard(total)
	}
}

Zero-copy pooled writes. Encode into a pooled uio.Buffer and transfer ownership with WriteOwned:

buf := uio.AcquireBuffer(n)
encode(buf.AvailableBuffer()[:n])
buf.CommitWrite(n)
if _, err := c.WriteOwned(buf); err == uio.ErrOutboundOverflow {
	uio.ReleaseBuffer(buf) // overflow is the only error that hands it back
}

Send files with sendfile(2). uio.SendFile(c, f, offset, count) sends a file range in order with the connection's other output, on the native backend with sendfile(2) (Linux, macOS, FreeBSD, DragonFly). A range the socket does not take at once is queued as a duplicate descriptor, not as memory, so f may be closed as soon as the call returns; ranges of 16 KiB or less are read into memory instead. A range is admitted whole while the queue is under MaxOutboundBuffered. Through protocol layers, on the stdio backend and on platforms without sendfile(2) the range is read into memory, within the queue's room or 4 MiB without a limit; a BlockingWriter's SendFile streams any length with backpressure, and io.Copy(bw, f) takes the same path.

func onRead(c uio.Conn) error {
	c.Discard(-1)
	c.Write(header)
	_, err := uio.SendFile(c, file, 0, -1) // the whole file, behind the header
	return err
}

Move a stream with splice(2). uio.Splice(ctx, dst, src, count) moves src's stream into dst — another connection, a BlockingWriter, a BlockingConn or an *os.File — and on Linux, between native connections and files, through a kernel pipe without copying it into user space. It reads src in pull mode (see NewBlockingReader), so src's OnRead runs no more. ubridge.Bridge relays its pairs the same way from their own turns.

Rules of the road

  • The inbound methods — Read, WriteTo, Peek, PeekChunk, Discard, InboundBuffered and ReserveInbound — may only be called inside the connection's own callback. Slices they return are valid until the callback returns or consumes more input; copy anything you hand to another goroutine. Builds with -race catch most misuse with a panic.
  • Write, Writev, WriteString, WriteOwned, Flush, Close, CloseWrite and Abort are safe from any goroutine.
  • CloseWrite shuts a stream connection's writing half after everything accepted has been sent; later writes return net.ErrClosed. On a layered connection it runs the layer's own CloseWrite inline — writing a TLS close_notify — so it may wait on I/O.
  • Close closes gracefully after everything accepted has been sent: writes are refused from the call, reads go on, and the connection releases once its queue is empty or LingerTimeout passes without progress, reporting leftover output as UnflushedError. Abort(cause) cuts the wait short at once and reports cause to OnClose.
  • OnBytesWritten can run concurrently with the connection's other callbacks.
  • OnClose means the connection is released, not that its socket is closed. With GOMAXPROCS of 33 or more, or Pollers above 8, an accepted connection's socket is closed on a goroutine of its event loop, so the peer can see the end shortly after OnClose. A positive SetLinger, a Control call or a listener SocketControl keeps the close before OnClose.
  • Events.Close only requests shutdown and returns at once; Serve returns once everything has stopped, or call Events.Wait from another goroutine.
  • Dial blocks the goroutine that calls it. From a callback, prefer dialing on a goroutine of your own.
  • On the stdio backend, Executor is not used.

The API reference has the full contract of every method.

License

Apache License 2.0

The Go gopher in the banner is based on the original design by Renée French, licensed under CC BY 4.0.

About

uio is a ultra-fast, lightweight, non-blocking, event-driven networking framework written in pure Go

Topics

Resources

Stars

23 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages