gnet

package module
v2.9.5 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2025 License: Apache-2.0 Imports: 31 Imported by: 232

README

gnet

English | 中文

🎉🎉🎉 Feel free to join the channels about gnet on the Discord Server.

📖 Introduction

gnet is an event-driven networking framework that is ultra-fast and lightweight. It is built from scratch by exploiting epoll and kqueue and it can achieve much higher performance with lower memory consumption than Go net in many specific scenarios.

gnet and net don't share the same philosophy in network programming. Thus, building network applications with gnet can be significantly different from building them with net, and the philosophies can't be reconciled. There are other similar products written in other programming languages in the community, such as libuv, netty, twisted, tornado, etc. which work in a similar pattern as gnet under the hood.

gnet is not designed to displace the Go net, but to create an alternative in the Go ecosystem for building performance-critical network services. As a result of which, gnet is not as comprehensive as Go net, it provides only the core functionality (via a concise set of APIs) required by a network application and it doesn't plan on becoming a coverall networking framework, as I think Go net has done a good enough job in that area.

gnet sells itself as a high-performance, lightweight, non-blocking, event-driven networking framework written in pure Go which works on the transport layer with TCP/UDP protocols and Unix Domain Socket. It enables developers to implement their own protocols(HTTP, RPC, WebSocket, Redis, etc.) of application layer upon gnet for building diversified network services. For instance, you get an HTTP Server if you implement HTTP protocol upon gnet while you have a Redis Server done with the implementation of Redis protocol upon gnet and so on.

gnet derives from the project: evio with much higher performance and more features.

🚀 Features

🦖 Milestone

  • High-performance event-driven looping based on a networking model of multiple threads/goroutines
  • Built-in goroutine pool powered by the library ants
  • Lock-free during the entire runtime
  • Concise and easy-to-use APIs
  • Efficient, reusable, and elastic memory buffer: (Elastic-)Ring-Buffer, Linked-List-Buffer and Elastic-Mixed-Buffer
  • Multiple protocols/IPC mechanisms: TCP, UDP, and Unix Domain Socket
  • Multiple load-balancing algorithms: Round-Robin, Source-Addr-Hash, and Least-Connections
  • Flexible ticker event
  • gnet client
  • Running on Linux, macOS, Windows, and *BSD: Darwin/DragonFlyBSD/FreeBSD/NetBSD/OpenBSD
  • Edge-triggered I/O support
  • Multiple network addresses binding
  • Support registering new connections to event-loops

🕊 Roadmap

  • TLS support
  • io_uring support
  • KCP support

Windows version of gnet should only be used in development for developing and testing, it shouldn't be used in production.

🎬 Getting started

gnet is available as a Go module and we highly recommend that you use gnet via Go Modules, with Go 1.11 Modules enabled (Go 1.11+), you can just simply add import "github.com/panjf2000/gnet/v2" to the codebase and run go mod download/go mod tidy or go [build|run|test] to download the necessary dependencies automatically.

With v2

go get -u github.com/panjf2000/gnet/v2

With v1

go get -u github.com/panjf2000/gnet

🎡 Use cases

The following corporations/organizations use gnet as the underlying network service in production.

If you're also using gnet in production, please help us enrich this list by opening a pull request.

📊 Performance

Benchmarks on TechEmpower

# Hardware Environment
* 28 HT Cores Intel(R) Xeon(R) Gold 5120 CPU @ 3.20GHz
* 32GB RAM
* Dedicated Cisco 10-gigabit Ethernet switch
* Debian 12 "bookworm"
* Go1.19.x linux/amd64

This is a leaderboard of the top 50 out of 486 frameworks that encompass various programming languages worldwide, in which gnet is ranked first.

This is the full framework ranking of Go and gnet tops all the other frameworks, which makes gnet the fastest networking framework in Go.

To see the full ranking list, visit TechEmpower Benchmark Round 22.

Note that the HTTP implementation of gnet on TechEmpower is half-baked and fine-tuned for benchmark purposes only and far from production-ready.

Contrasts to the similar networking libraries

On Linux (epoll)

Environment

# Machine information
        OS : Ubuntu 20.04/x86_64
       CPU : 8 CPU cores, AMD EPYC 7K62 48-Core Processor
    Memory : 16.0 GiB

# Go version and settings
Go Version : go1.17.2 linux/amd64
GOMAXPROCS : 8

# Benchmark parameters
TCP connections : 1000/2000/5000/10000
Packet size     : 512/1024/2048/4096/8192/16384/32768/65536 bytes
Test duration   : 15s

On MacOS (kqueue)

Environment

# Machine information
        OS : MacOS Big Sur/x86_64
       CPU : 6 CPU cores, Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory : 16.0 GiB

# Go version and settings
Go Version : go1.16.5 darwin/amd64
GOMAXPROCS : 12

# Benchmark parameters
TCP connections : 300/400/500/600/700
Packet size     : 512/1024/2048/4096/8192 bytes
Test duration   : 15s

Comparison with Rust

⚠️ License

The source code of gnet should be distributed under the Apache-2.0 license.

👏 Contributors

Please read the Contributing Guidelines before opening a PR and thank you to all the developers who already made contributions to gnet!

⚓ Relevant Articles

☕️ Buy me a coffee

Please be sure to leave your name, GitHub account, or other social media accounts when you donate by the following means so that I can add it to the list of donors as a token of my appreciation.

By me coffee Patreon OpenCollective

🔑 JetBrains OS licenses

gnet has been being developed with GoLand IDE under the free JetBrains Open Source license(s) granted by JetBrains s.r.o., hence I would like to express my thanks here.

JetBrains logo.

🔋 Sponsorship

This project is supported by:

Documentation

Overview

Package gnet implements a high-performance, lightweight, non-blocking, event-driven networking framework written in pure Go.

Visit https://gnet.host/ for more details about gnet.

Index

Constants

This section is empty.

Variables

View Source
var MaxStreamBufferCap = 64 * 1024 // 64KB

MaxStreamBufferCap is the default buffer size for each stream-oriented connection(TCP/Unix).

Functions

func FromContext added in v2.8.0

func FromContext(ctx context.Context) any

FromContext retrieves context value of the Conn stored in ctx, if any.

func FromNetAddrContext added in v2.8.0

func FromNetAddrContext(ctx context.Context) (net.Addr, bool)

FromNetAddrContext retrieves the net.Addr value from ctx, if any.

func FromNetConnContext added in v2.8.0

func FromNetConnContext(ctx context.Context) (net.Conn, bool)

FromNetConnContext retrieves the net.Conn value from ctx, if any.

func NewContext added in v2.8.0

func NewContext(ctx context.Context, v any) context.Context

NewContext returns a new context.Context that carries the value that will be attached to the Conn.

func NewNetAddrContext added in v2.8.0

func NewNetAddrContext(ctx context.Context, a net.Addr) context.Context

NewNetAddrContext returns a new context.Context that carries the net.Addr value.

func NewNetConnContext added in v2.8.0

func NewNetConnContext(ctx context.Context, c net.Conn) context.Context

NewNetConnContext returns a new context.Context that carries the net.Conn value.

func Rotate added in v2.5.0

func Rotate(eventHandler EventHandler, addrs []string, opts ...Option) error

Rotate is like Run but accepts multiple network addresses.

func Run

func Run(eventHandler EventHandler, protoAddr string, opts ...Option) error

Run starts handling events on the specified address.

Address should use a scheme prefix and be formatted like `tcp://192.168.0.10:9851` or `unix://socket`. Valid network schemes:

tcp   - bind to both IPv4 and IPv6
tcp4  - IPv4
tcp6  - IPv6
udp   - bind to both IPv4 and IPv6
udp4  - IPv4
udp6  - IPv6
unix  - Unix Domain Socket

The "tcp" network scheme is assumed when one is not specified.

func Stop deprecated

func Stop(ctx context.Context, protoAddr string) error

Stop gracefully shuts down the engine without interrupting any active event-loops, it waits indefinitely for connections and event-loops to be closed and then shuts down.

Deprecated: The global Stop only shuts down the last registered Engine with the same protocol and IP:Port as the previous Engine's, which can lead to leaks of Engine if you invoke gnet.Run multiple times using the same protocol and IP:Port under the condition that WithReuseAddr(true) and WithReusePort(true) are enabled. Use Engine.Stop instead.

Types

type Action

type Action int

Action is an action that occurs after the completion of an event.

const (
	// None indicates that no action should occur following an event.
	None Action = iota

	// Close closes the connection.
	Close

	// Shutdown shutdowns the engine.
	Shutdown
)

type AsyncCallback

type AsyncCallback func(c Conn, err error) error

AsyncCallback is a callback that will be invoked after the asynchronous function finishes.

Note that the parameter gnet.Conn might have been already released when it's UDP protocol, thus it shouldn't be accessed. This callback will be executed in event-loop, thus it must not block, otherwise, it blocks the event-loop.

type BuiltinEventEngine

type BuiltinEventEngine struct{}

BuiltinEventEngine is a built-in implementation of EventHandler which feeds each method with an empty implementation, you can embed it within your custom struct when you don't intend to implement the entire EventHandler.

func (*BuiltinEventEngine) OnBoot

func (*BuiltinEventEngine) OnBoot(_ Engine) (action Action)

OnBoot fires when the engine is ready for accepting connections. The parameter engine has information and various utilities.

func (*BuiltinEventEngine) OnClose

func (*BuiltinEventEngine) OnClose(_ Conn, _ error) (action Action)

OnClose fires when a connection has been closed. The parameter err is the last known connection error.

func (*BuiltinEventEngine) OnOpen

func (*BuiltinEventEngine) OnOpen(_ Conn) (out []byte, action Action)

OnOpen fires when a new connection has been opened. The parameter out is the return value which is going to be sent back to the remote.

func (*BuiltinEventEngine) OnShutdown

func (*BuiltinEventEngine) OnShutdown(_ Engine)

OnShutdown fires when the engine is being shut down, it is called right after all event-loops and connections are closed.

func (*BuiltinEventEngine) OnTick

func (*BuiltinEventEngine) OnTick() (delay time.Duration, action Action)

OnTick fires immediately after the engine starts and will fire again following the duration specified by the delay return value.

func (*BuiltinEventEngine) OnTraffic

func (*BuiltinEventEngine) OnTraffic(_ Conn) (action Action)

OnTraffic fires when a local socket receives data from the remote.

type Client

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

Client of gnet.

func NewClient

func NewClient(eh EventHandler, opts ...Option) (cli *Client, err error)

NewClient creates an instance of Client.

func (*Client) Dial

func (cli *Client) Dial(network, address string) (Conn, error)

Dial is like net.Dial().

func (*Client) DialContext added in v2.4.0

func (cli *Client) DialContext(network, address string, ctx any) (Conn, error)

DialContext is like Dial but also accepts an empty interface ctx that can be obtained later via Conn.Context.

func (*Client) Enroll added in v2.1.0

func (cli *Client) Enroll(c net.Conn) (Conn, error)

Enroll converts a net.Conn to gnet.Conn and then adds it into the Client.

func (*Client) EnrollContext added in v2.4.0

func (cli *Client) EnrollContext(c net.Conn, ctx any) (Conn, error)

EnrollContext is like Enroll but also accepts an empty interface ctx that can be obtained later via Conn.Context.

func (*Client) Start

func (cli *Client) Start() error

Start starts the client event-loop, handing IO events.

func (*Client) Stop

func (cli *Client) Stop() error

Stop stops the client event-loop.

type Conn

type Conn interface {
	Reader // all methods in Reader are not concurrency-safe.
	Writer // some methods in Writer are concurrency-safe, some are not.
	Socket // all methods in Socket are concurrency-safe.

	// Context returns a user-defined context, it's not concurrency-safe,
	// you must invoke it within any method in EventHandler.
	Context() (ctx any)

	// EventLoop returns the event-loop that the connection belongs to.
	// The returned EventLoop is concurrency-safe.
	EventLoop() EventLoop

	// SetContext sets a user-defined context, it's not concurrency-safe,
	// you must invoke it within any method in EventHandler.
	SetContext(ctx any)

	// LocalAddr is the connection's local socket address, it's not concurrency-safe,
	// you must invoke it within any method in EventHandler.
	LocalAddr() net.Addr

	// RemoteAddr is the connection's remote address, it's not concurrency-safe,
	// you must invoke it within any method in EventHandler.
	RemoteAddr() net.Addr

	// Wake triggers an OnTraffic event for the current connection, it's concurrency-safe.
	Wake(callback AsyncCallback) error

	// CloseWithCallback closes the current connection, it's concurrency-safe.
	// Usually you should provide a non-nil callback for this method,
	// otherwise your better choice is Close().
	CloseWithCallback(callback AsyncCallback) error

	// Close closes the current connection, implements net.Conn, it's concurrency-safe.
	Close() error

	// SetDeadline implements net.Conn.
	SetDeadline(time.Time) error

	// SetReadDeadline implements net.Conn.
	SetReadDeadline(time.Time) error

	// SetWriteDeadline implements net.Conn.
	SetWriteDeadline(time.Time) error
}

Conn is an interface of underlying connection.

type Engine

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

Engine represents an engine context which provides some functions.

func (Engine) CountConnections

func (e Engine) CountConnections() (count int)

CountConnections counts the number of currently active connections and returns it.

func (Engine) Dup

func (e Engine) Dup() (fd int, err error)

Dup returns a copy of the underlying file descriptor of listener. It is the caller's responsibility to close dupFD when finished. Closing listener does not affect dupFD, and closing dupFD does not affect listener.

Note that this method is only available when the engine has only one listener.

func (Engine) DupListener added in v2.8.0

func (e Engine) DupListener(network, addr string) (int, error)

DupListener is like Dup, but it duplicates the listener with the given network and address. This is useful when there are multiple listeners.

func (Engine) Register added in v2.8.0

func (e Engine) Register(ctx context.Context) (<-chan RegisteredResult, error)

Register registers the new connection to the event-loop that is chosen based off of the algorithm set by WithLoadBalancing. You should call either of the NewNetConnContext or NewNetAddrContext and pass the returned context to this method. net.Conn will precede net.Addr if both are present in the context.

Note that you need to switch to another load-balancing algorithm over the default RoundRobin when starting the engine, to avoid data race issue if you plan on calling this method from somewhere later on.

func (Engine) Stop added in v2.2.0

func (e Engine) Stop(ctx context.Context) error

Stop gracefully shuts down this Engine without interrupting any active event-loops, it waits indefinitely for connections and event-loops to be closed and then shuts down.

func (Engine) Validate added in v2.3.0

func (e Engine) Validate() error

Validate checks whether the engine is available.

type EventHandler

type EventHandler interface {
	// OnBoot fires when the engine is ready for accepting connections.
	// The parameter engine has information and various utilities.
	OnBoot(eng Engine) (action Action)

	// OnShutdown fires when the engine is being shut down, it is called right after
	// all event-loops and connections are closed.
	OnShutdown(eng Engine)

	// OnOpen fires when a new connection has been opened.
	//
	// The Conn c has information about the connection such as its local and remote addresses.
	// The parameter out is the return value which is going to be sent back to the remote.
	// Sending large amounts of data back to the remote in OnOpen is usually not recommended.
	OnOpen(c Conn) (out []byte, action Action)

	// OnClose fires when a connection has been closed.
	// The parameter err is the last known connection error.
	OnClose(c Conn, err error) (action Action)

	// OnTraffic fires when a socket receives data from the remote.
	//
	// Also check out the comments on Reader and Writer interfaces.
	OnTraffic(c Conn) (action Action)

	// OnTick fires immediately after the engine starts and will fire again
	// following the duration specified by the delay return value.
	OnTick() (delay time.Duration, action Action)
}

EventHandler represents the engine events' callbacks for the Run call. Each event has an Action return value that is used manage the state of the connection and engine.

type EventLoop added in v2.8.0

type EventLoop interface {
	// Register connects to the given address and registers the connection to the current event-loop,
	// it's concurrency-safe.
	Register(ctx context.Context, addr net.Addr) (<-chan RegisteredResult, error)
	// Enroll is like Register, but it accepts an established net.Conn instead of a net.Addr,
	// it's concurrency-safe.
	Enroll(ctx context.Context, c net.Conn) (<-chan RegisteredResult, error)
	// Execute will execute the given runnable on the event-loop at some time in the future,
	// it's concurrency-safe.
	Execute(ctx context.Context, runnable Runnable) error
	// Schedule is like Execute, but it allows you to specify when the runnable is executed.
	// In other words, the runnable will be executed when the delay duration is reached,
	// it's concurrency-safe.
	// TODO(panjf2000): not supported yet, implement this.
	Schedule(ctx context.Context, runnable Runnable, delay time.Duration) error

	// Close closes the given Conn that belongs to the current event-loop.
	// It must be called on the same event-loop that the connection belongs to.
	// This method is not concurrency-safe, you must invoke it on the event loop.
	Close(Conn) error
}

EventLoop provides a set of methods for manipulating the event-loop.

type LoadBalancing

type LoadBalancing int

LoadBalancing represents the type of load-balancing algorithm.

const (
	// RoundRobin assigns the next accepted connection to the event-loop by polling event-loop list.
	RoundRobin LoadBalancing = iota

	// LeastConnections assigns the next accepted connection to the event-loop that is
	// serving the least number of active connections at the current time.
	LeastConnections

	// SourceAddrHash assigns the next accepted connection to the event-loop by hashing the remote address.
	SourceAddrHash
)

type Option

type Option func(opts *Options)

Option is a function that will set up option.

func WithBindToDevice added in v2.6.0

func WithBindToDevice(iface string) Option

WithBindToDevice sets the name of the interface to which the listening socket will be bound.

It is only available on Linux at the moment, an error will therefore be returned when setting this option on non-linux platforms.

func WithEdgeTriggeredIO added in v2.5.0

func WithEdgeTriggeredIO(et bool) Option

WithEdgeTriggeredIO enables the edge-triggered I/O for the underlying epoll/kqueue event-loop.

func WithEdgeTriggeredIOChunk added in v2.6.0

func WithEdgeTriggeredIOChunk(chunk int) Option

WithEdgeTriggeredIOChunk sets the number of bytes that `gnet` can read/write up to in one event loop of ET.

func WithLoadBalancing

func WithLoadBalancing(lb LoadBalancing) Option

WithLoadBalancing picks the load-balancing algorithm for gnet engine.

func WithLockOSThread

func WithLockOSThread(lockOSThread bool) Option

WithLockOSThread enables LockOSThread mode for I/O event-loops.

func WithLogLevel

func WithLogLevel(lvl logging.Level) Option

WithLogLevel specifies the logging level for the local logging file.

func WithLogPath

func WithLogPath(fileName string) Option

WithLogPath specifies a local path for logging file.

func WithLogger

func WithLogger(logger logging.Logger) Option

WithLogger specifies a customized logger.

func WithMulticastInterfaceIndex added in v2.2.0

func WithMulticastInterfaceIndex(idx int) Option

WithMulticastInterfaceIndex sets the interface name where UDP multicast sockets will be bound to.

func WithMulticore

func WithMulticore(multicore bool) Option

WithMulticore enables multi-cores mode for gnet engine.

func WithNumEventLoop

func WithNumEventLoop(numEventLoop int) Option

WithNumEventLoop sets the number of event loops for gnet engine.

func WithOptions

func WithOptions(options Options) Option

WithOptions sets up all options.

func WithReadBufferCap

func WithReadBufferCap(readBufferCap int) Option

WithReadBufferCap sets ReadBufferCap for reading bytes.

func WithReuseAddr

func WithReuseAddr(reuseAddr bool) Option

WithReuseAddr sets SO_REUSEADDR socket option.

func WithReusePort

func WithReusePort(reusePort bool) Option

WithReusePort sets SO_REUSEPORT socket option.

func WithSocketRecvBuffer

func WithSocketRecvBuffer(recvBuf int) Option

WithSocketRecvBuffer sets the maximum socket receive buffer of kernel in bytes.

func WithSocketSendBuffer

func WithSocketSendBuffer(sendBuf int) Option

WithSocketSendBuffer sets the maximum socket send buffer of kernel in bytes.

func WithTCPKeepAlive

func WithTCPKeepAlive(tcpKeepAlive time.Duration) Option

WithTCPKeepAlive enables the TCP keep-alive mechanism and sets its values.

func WithTCPKeepCount added in v2.9.0

func WithTCPKeepCount(tcpKeepCount int) Option

WithTCPKeepCount sets the number of keep-alive probes that will be sent before the connection is considered dead and dropped.

func WithTCPKeepInterval added in v2.9.0

func WithTCPKeepInterval(tcpKeepInterval time.Duration) Option

WithTCPKeepInterval sets the interval between TCP keep-alive probes.

func WithTCPNoDelay

func WithTCPNoDelay(tcpNoDelay TCPSocketOpt) Option

WithTCPNoDelay enable/disable the TCP_NODELAY socket option.

func WithTicker

func WithTicker(ticker bool) Option

WithTicker indicates whether a ticker is currently set.

func WithWriteBufferCap

func WithWriteBufferCap(writeBufferCap int) Option

WithWriteBufferCap sets WriteBufferCap for pending bytes.

type Options

type Options struct {
	// LB represents the load-balancing algorithm used when assigning new connections
	// to event loops. This option is server-only, and it is not applicable to the client.
	LB LoadBalancing

	// ReuseAddr indicates whether to set the SO_REUSEADDR socket option.
	// This option is server-only.
	ReuseAddr bool

	// ReusePort indicates whether to set the SO_REUSEPORT socket option.
	// This option is server-only.
	ReusePort bool

	// MulticastInterfaceIndex is the index of the interface name where the multicast UDP addresses will be bound to.
	// This option is server-only.
	MulticastInterfaceIndex int

	// BindToDevice is the name of the interface to which the listening socket will be bound.
	// It is only available on Linux at the moment, an error will therefore be returned when
	// setting this option on non-linux platforms.
	// This option is server-only.
	BindToDevice string

	// Multicore indicates whether the engine will be effectively created with multi-cores, if so,
	// then you must take care with synchronizing memory between all event callbacks; otherwise,
	// it will run the engine with single thread. The number of threads in the engine will be
	// automatically assigned to the number of usable logical CPUs that can be leveraged by the
	// current process.
	Multicore bool

	// NumEventLoop is set up to start the given number of event-loop goroutines.
	// Note that a non-negative NumEventLoop will override Multicore.
	NumEventLoop int

	// ReadBufferCap is the maximum number of bytes that can be read from the remote when the readable event comes.
	// The default value is 64KB, it can either be reduced to avoid starving the subsequent connections or increased
	// to read more data from a socket.
	//
	// Note that ReadBufferCap will always be converted to the least power of two integer value greater than
	// or equal to its real amount.
	ReadBufferCap int

	// WriteBufferCap is the maximum number of bytes that a static outbound buffer can hold,
	// if the data exceeds this value, the overflow bytes will be stored in the elastic linked list buffer.
	// The default value is 64KB.
	//
	// Note that WriteBufferCap will always be converted to the least power of two integer value greater than
	// or equal to its real amount.
	WriteBufferCap int

	// LockOSThread is used to determine whether each I/O event-loop should be associated to an OS thread,
	// it is useful when you need some kind of mechanisms like thread local storage, or invoke certain C
	// libraries (such as graphics lib: GLib) that require thread-level manipulation via cgo, or want all I/O
	// event-loops to actually run in parallel for a potential higher performance.
	LockOSThread bool

	// Ticker indicates whether the ticker has been set up.
	Ticker bool

	// TCPKeepAlive enables the TCP keep-alive mechanism (SO_KEEPALIVE) and set its value
	// on TCP_KEEPIDLE.
	// When TCPKeepInterval is not set, 1/5 of TCPKeepAlive will be set on TCP_KEEPINTVL,
	// and 5 will be set on TCP_KEEPCNT if TCPKeepCount is not assigned to a positive value.
	TCPKeepAlive time.Duration

	// TCPKeepInterval is the value for TCP_KEEPINTVL, it's the interval between
	// TCP keep-alive probes.
	TCPKeepInterval time.Duration

	// TCPKeepCount is the number of keep-alive probes that will be sent before
	// the connection is considered dead and dropped.
	TCPKeepCount int

	// TCPNoDelay controls whether the operating system should delay
	// packet transmission in hopes of sending fewer packets (Nagle's algorithm).
	// When this option is assigned to TCPNoDelay, TCP_NODELAY socket option will
	// be turned on, on the contrary, if it is assigned to TCPDelay, the socket
	// option will be turned off.
	//
	// The default is TCPNoDelay, meaning that TCP_NODELAY is turned on and data
	// will not be buffered but sent as soon as possible after a write operation.
	TCPNoDelay TCPSocketOpt

	// SocketRecvBuffer sets the maximum socket receive buffer of kernel in bytes.
	SocketRecvBuffer int

	// SocketSendBuffer sets the maximum socket send buffer of kernel in bytes.
	SocketSendBuffer int

	// LogPath specifies a local path where logs will be written, this is the easiest
	// way to set up logging, gnet instantiates a default uber-go/zap logger with this
	// given log path, you are also allowed to employ your own logger during the lifetime
	// by implementing the following logging.Logger interface.
	//
	// Note that this option can be overridden by a non-nil option Logger.
	LogPath string

	// LogLevel specifies the logging level, it should be used along with LogPath.
	LogLevel logging.Level

	// Logger is the customized logger for logging info, if it is not set,
	// then gnet will use the default logger powered by go.uber.org/zap.
	Logger logging.Logger

	// EdgeTriggeredIO enables the edge-triggered I/O for the underlying epoll/kqueue event-loop.
	// Don't enable it unless you are 100% sure what you are doing.
	// Note that this option is only available for stream-oriented protocol.
	EdgeTriggeredIO bool

	// EdgeTriggeredIOChunk specifies the number of bytes that `gnet` can
	// read/write up to in one event loop of ET. This option implies
	// EdgeTriggeredIO when it is set to a value greater than 0.
	// If EdgeTriggeredIO is set to true and EdgeTriggeredIOChunk is not set,
	// 1MB is used. The value of EdgeTriggeredIOChunk must be a power of 2,
	// otherwise, it will be rounded up to the nearest power of 2.
	EdgeTriggeredIOChunk int
}

Options are configurations for the gnet application.

type Reader

type Reader interface {
	io.Reader
	io.WriterTo

	// Next returns the next n bytes and advances the inbound buffer.
	// buf must not be used in a new goroutine. Otherwise, use Read instead.
	//
	// If the number of the available bytes is less than requested,
	// a pair of (0, io.ErrShortBuffer) is returned.
	Next(n int) (buf []byte, err error)

	// Peek returns the next n bytes without advancing the inbound buffer,
	// the returned bytes remain valid until a Discard is called.
	// buf must neither be used in a new goroutine nor anywhere after the call
	// to Discard, make a copy of buf manually or use Read otherwise.
	//
	// If the number of the available bytes is less than requested,
	// a pair of (0, io.ErrShortBuffer) is returned.
	Peek(n int) (buf []byte, err error)

	// Discard advances the inbound buffer with next n bytes, returning the number of bytes discarded.
	Discard(n int) (discarded int, err error)

	// InboundBuffered returns the number of bytes that can be read from the current buffer.
	InboundBuffered() int
}

Reader is an interface that consists of a number of methods for reading that Conn must implement.

Note that the methods in this interface are not concurrency-safe for concurrent use, you must invoke them within any method in EventHandler.

type RegisteredResult added in v2.8.0

type RegisteredResult struct {
	Conn Conn
	Err  error
}

RegisteredResult is the result of a Register call.

type Runnable added in v2.8.0

type Runnable interface {
	// Run is about to be executed by the event-loop.
	Run(ctx context.Context) error
}

Runnable defines the common protocol of an execution on an event-loop. This interface should be implemented and passed to an event-loop in some way, then the event-loop will invoke Run to perform the execution. !!!Caution: Run must not contain any blocking operations like heavy disk or network I/O, or else it will block the event-loop.

type RunnableFunc added in v2.8.0

type RunnableFunc func(ctx context.Context) error

RunnableFunc is an adapter to allow the use of ordinary function as a Runnable.

func (RunnableFunc) Run added in v2.8.0

func (fn RunnableFunc) Run(ctx context.Context) error

Run executes the RunnableFunc itself.

type Socket

type Socket interface {

	// Fd returns the underlying file descriptor.
	Fd() int

	// Dup returns a copy of the underlying file descriptor.
	// It is the caller's responsibility to close fd when finished.
	// Closing c does not affect fd, and closing fd does not affect c.
	//
	// The returned file descriptor is different from the
	//  connection. Attempting to change the properties of the original
	// using this duplicate may or may not have the desired effect.
	Dup() (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

	// SetLinger sets the behavior of Close on a connection which still
	// has data waiting to be sent or to be acknowledged.
	//
	// If secs < 0 (the default), the operating system finishes sending the
	// data in the background.
	//
	// If secs == 0, the operating system discards any unsent or
	// unacknowledged data.
	//
	// If secs > 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

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

	// SetKeepAlive enables/disables the TCP keepalive with all socket options:
	// TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT. idle is the value for TCP_KEEPIDLE,
	// intvl is the value for TCP_KEEPINTVL, cnt is the value for TCP_KEEPCNT,
	// ignored when enabled is false.
	//
	// With TCP keep-alive enabled, idle is the time (in seconds) the connection
	// needs to remain idle before TCP starts sending keep-alive probes,
	// intvl is the time (in seconds) between individual keep-alive probes.
	// TCP will drop the connection after sending cnt probes without getting
	// any replies from the peer; then the socket is destroyed, and OnClose
	// is triggered.
	//
	// If one of idle, intvl, or cnt is less than 1, an error is returned.
	SetKeepAlive(enabled bool, idle, intvl time.Duration, cnt 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
}

Socket is a set of functions which manipulate the underlying file descriptor of a connection.

Note that the methods in this interface are concurrency-safe for concurrent use, you don't have to invoke them within any method in EventHandler.

type TCPSocketOpt

type TCPSocketOpt int

TCPSocketOpt is the type of TCP socket options.

const (
	TCPNoDelay TCPSocketOpt = iota
	TCPDelay
)

Available TCP socket options.

type Writer

type Writer interface {
	io.Writer     // not concurrency-safe
	io.ReaderFrom // not concurrency-safe

	// SendTo transmits a message to the given address, it's not concurrency-safe.
	// It is available only for UDP sockets, an ErrUnsupportedOp will be returned
	// when it is called on a non-UDP socket.
	// This method should be used only when you need to send a message to a specific
	// address over the UDP socket, otherwise you should use Conn.Write() instead.
	SendTo(buf []byte, addr net.Addr) (n int, err error)

	// Writev writes multiple byte slices to remote synchronously, it's not concurrency-safe,
	// you must invoke it within any method in EventHandler.
	Writev(bs [][]byte) (n int, err error)

	// Flush writes any buffered data to the underlying connection, it's not concurrency-safe,
	// you must invoke it within any method in EventHandler.
	Flush() error

	// OutboundBuffered returns the number of bytes that can be read from the current buffer.
	// it's not concurrency-safe, you must invoke it within any method in EventHandler.
	OutboundBuffered() int

	// AsyncWrite writes bytes to remote asynchronously, it's concurrency-safe,
	// you don't have to invoke it within any method in EventHandler,
	// usually you would call it in an individual goroutine.
	//
	// Note that it will go synchronously with UDP, so it is needless to call
	// this asynchronous method, we may disable this method for UDP and just
	// return ErrUnsupportedOp in the future, therefore, please don't rely on
	// this method to do something important under UDP, if you're working with UDP,
	// just call Conn.Write to send back your data.
	AsyncWrite(buf []byte, callback AsyncCallback) (err error)

	// AsyncWritev writes multiple byte slices to remote asynchronously,
	// you don't have to invoke it within any method in EventHandler,
	// usually you would call it in an individual goroutine.
	AsyncWritev(bs [][]byte, callback AsyncCallback) (err error)
}

Writer is an interface that consists of a number of methods for writing that Conn must implement.

Directories

Path Synopsis
internal
gfd
Package gfd provides a structure GFD to store the fd, eventloop index, connStore indexes and some other information.
Package gfd provides a structure GFD to store the fd, eventloop index, connStore indexes and some other information.
pkg
bs
Package bs provides a few handy bytes/string functions.
Package bs provides a few handy bytes/string functions.
buffer/elastic
Package elastic implements an elastic ring-buffer.
Package elastic implements an elastic ring-buffer.
buffer/linkedlist
Package linkedlist implements a memory-reusable linked list of byte slices.
Package linkedlist implements a memory-reusable linked list of byte slices.
buffer/ring
Package ring implements a memory-efficient circular buffer.
Package ring implements a memory-efficient circular buffer.
errors
Package errors defines common errors for gnet.
Package errors defines common errors for gnet.
io
Package io provides some handy network I/O functions.
Package io provides some handy network I/O functions.
logging
Package logging provides logging functionality for gnet applications, it sets up a default logger (powered by go.uber.org/zap) that is about to be used by your gnet application.
Package logging provides logging functionality for gnet applications, it sets up a default logger (powered by go.uber.org/zap) that is about to be used by your gnet application.
math
Package math provides a few fast math functions.
Package math provides a few fast math functions.
netpoll
Package netpoll provides a portable event-driven interface for network I/O.
Package netpoll provides a portable event-driven interface for network I/O.
pool/bytebuffer
Package bytebuffer is a pool of bytebufferpool.ByteBuffer.
Package bytebuffer is a pool of bytebufferpool.ByteBuffer.
pool/byteslice
Package byteslice implements a pool of byte slices consisting of sync.Pool's that collect byte slices with different length sizes from 0 to 32 in powers of 2.
Package byteslice implements a pool of byte slices consisting of sync.Pool's that collect byte slices with different length sizes from 0 to 32 in powers of 2.
pool/goroutine
Package goroutine is a wrapper of github.com/panjf2000/ants with some practical configurations.
Package goroutine is a wrapper of github.com/panjf2000/ants with some practical configurations.
pool/ringbuffer
Package ringbuffer implements a GC-friendly pool of ring buffers.
Package ringbuffer implements a GC-friendly pool of ring buffers.
queue
Package queue delivers an implementation of lock-free concurrent queue based on the algorithm presented by Maged M. Michael and Michael L. Scot.
Package queue delivers an implementation of lock-free concurrent queue based on the algorithm presented by Maged M. Michael and Michael L. Scot.
socket
Package socket provides some handy socket-related functions.
Package socket provides some handy socket-related functions.

Jump to

Keyboard shortcuts

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