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 ¶
- Variables
- func FromContext(ctx context.Context) any
- func FromNetAddrContext(ctx context.Context) (net.Addr, bool)
- func FromNetConnContext(ctx context.Context) (net.Conn, bool)
- func NewContext(ctx context.Context, v any) context.Context
- func NewNetAddrContext(ctx context.Context, a net.Addr) context.Context
- func NewNetConnContext(ctx context.Context, c net.Conn) context.Context
- func Rotate(eventHandler EventHandler, addrs []string, opts ...Option) error
- func Run(eventHandler EventHandler, protoAddr string, opts ...Option) error
- func Stop(ctx context.Context, protoAddr string) errordeprecated
- type Action
- type AsyncCallback
- type BuiltinEventEngine
- func (*BuiltinEventEngine) OnBoot(_ Engine) (action Action)
- func (*BuiltinEventEngine) OnClose(_ Conn, _ error) (action Action)
- func (*BuiltinEventEngine) OnOpen(_ Conn) (out []byte, action Action)
- func (*BuiltinEventEngine) OnShutdown(_ Engine)
- func (*BuiltinEventEngine) OnTick() (delay time.Duration, action Action)
- func (*BuiltinEventEngine) OnTraffic(_ Conn) (action Action)
- type Client
- func (cli *Client) Dial(network, address string) (Conn, error)
- func (cli *Client) DialContext(network, address string, ctx any) (Conn, error)
- func (cli *Client) Enroll(c net.Conn) (Conn, error)
- func (cli *Client) EnrollContext(c net.Conn, ctx any) (Conn, error)
- func (cli *Client) Start() error
- func (cli *Client) Stop() error
- type Conn
- type Engine
- func (e Engine) CountConnections() (count int)
- func (e Engine) Dup() (fd int, err error)
- func (e Engine) DupListener(network, addr string) (int, error)
- func (e Engine) Register(ctx context.Context) (<-chan RegisteredResult, error)
- func (e Engine) Stop(ctx context.Context) error
- func (e Engine) Validate() error
- type EventHandler
- type EventLoop
- type LoadBalancing
- type Option
- func WithBindToDevice(iface string) Option
- func WithEdgeTriggeredIO(et bool) Option
- func WithEdgeTriggeredIOChunk(chunk int) Option
- func WithLoadBalancing(lb LoadBalancing) Option
- func WithLockOSThread(lockOSThread bool) Option
- func WithLogLevel(lvl logging.Level) Option
- func WithLogPath(fileName string) Option
- func WithLogger(logger logging.Logger) Option
- func WithMulticastInterfaceIndex(idx int) Option
- func WithMulticore(multicore bool) Option
- func WithNumEventLoop(numEventLoop int) Option
- func WithOptions(options Options) Option
- func WithReadBufferCap(readBufferCap int) Option
- func WithReuseAddr(reuseAddr bool) Option
- func WithReusePort(reusePort bool) Option
- func WithSocketRecvBuffer(recvBuf int) Option
- func WithSocketSendBuffer(sendBuf int) Option
- func WithTCPKeepAlive(tcpKeepAlive time.Duration) Option
- func WithTCPKeepCount(tcpKeepCount int) Option
- func WithTCPKeepInterval(tcpKeepInterval time.Duration) Option
- func WithTCPNoDelay(tcpNoDelay TCPSocketOpt) Option
- func WithTicker(ticker bool) Option
- func WithWriteBufferCap(writeBufferCap int) Option
- type Options
- type Reader
- type RegisteredResult
- type Runnable
- type RunnableFunc
- type Socket
- type TCPSocketOpt
- type Writer
Constants ¶
This section is empty.
Variables ¶
var MaxStreamBufferCap = 64 * 1024 // 64KB
MaxStreamBufferCap is the default buffer size for each stream-oriented connection(TCP/Unix).
Functions ¶
func FromContext ¶
FromContext retrieves context value of the Conn stored in ctx, if any.
func FromNetAddrContext ¶
FromNetAddrContext retrieves the net.Addr value from ctx, if any.
func FromNetConnContext ¶
FromNetConnContext retrieves the net.Conn value from ctx, if any.
func NewContext ¶
NewContext returns a new context.Context that carries the value that will be attached to the Conn.
func NewNetAddrContext ¶
NewNetAddrContext returns a new context.Context that carries the net.Addr value.
func NewNetConnContext ¶
NewNetConnContext returns a new context.Context that carries the net.Conn value.
func Rotate ¶
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.
func Stop
deprecated
Stop gracefully shuts down the engine without interrupting any active event-loops.
Deprecated: The global Stop only shuts down the last registered Engine with the same protocol and IP:Port. If you invoke gnet.Run multiple times with the same address (using WithReuseAddr/WithReusePort), previous engines are leaked in allEngines. Use Engine.Stop instead.
FIX S-3: The previous implementation had two bugs:
- When the engine was not found in allEngines, it returned ErrEngineInShutdown, which is semantically wrong (the engine is simply not found, not shut down). Fixed to return ErrEmptyEngine to accurately describe the situation.
- It called eng.shutdown(nil) and then immediately checked eng.isShutdown(), which is a race: shutdown() only cancels the context, while isShutdown() is set to true only after eng.stop() completes — so the check always returned false and the function incorrectly fell through to the poll loop regardless. Fixed by removing the premature isShutdown() check entirely and letting the poll loop below handle the correct terminal state.
FIX S-4: If two goroutines call gnet.Run with the same address concurrently, a plain Store would overwrite the first entry in allEngines without shutting the first engine down — causing a goroutine and fd leak, and leaving an engine that gnet.Stop can no longer reach. run() now detects the clash with LoadOrStore before it overwrites, and warns. The previous version of this comment described that fix while the code still did an unconditional Store (see engine_unix.go and engine_windows.go, where the FIX S-4 handling actually lives).
Types ¶
type AsyncCallback ¶
AsyncCallback is a callback that will be invoked after the asynchronous function finishes.
type BuiltinEventEngine ¶
type BuiltinEventEngine struct{}
BuiltinEventEngine is a built-in implementation of EventHandler which feeds each method with an empty implementation.
func (*BuiltinEventEngine) OnBoot ¶
func (*BuiltinEventEngine) OnBoot(_ Engine) (action Action)
func (*BuiltinEventEngine) OnClose ¶
func (*BuiltinEventEngine) OnClose(_ Conn, _ error) (action Action)
func (*BuiltinEventEngine) OnOpen ¶
func (*BuiltinEventEngine) OnOpen(_ Conn) (out []byte, action Action)
func (*BuiltinEventEngine) OnShutdown ¶
func (*BuiltinEventEngine) OnShutdown(_ Engine)
func (*BuiltinEventEngine) OnTick ¶
func (*BuiltinEventEngine) OnTick() (delay time.Duration, action Action)
func (*BuiltinEventEngine) OnTraffic ¶
func (*BuiltinEventEngine) OnTraffic(_ Conn) (action Action)
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) DialContext ¶
DialContext is like Dial but also accepts an empty interface ctx that can be obtained later via Conn.Context.
func (*Client) EnrollContext ¶
EnrollContext is like Enroll but also accepts an empty interface ctx that can be obtained later via Conn.Context.
type Conn ¶
type Conn interface {
Reader
Writer
Socket
Context() (ctx any)
SafeContext() (ctx any)
EventLoop() EventLoop
SetContext(ctx any)
SetSafeContext(ctx any)
LocalAddr() net.Addr
RemoteAddr() net.Addr
Wake(callback AsyncCallback) error
CloseWithCallback(callback AsyncCallback) error
Close() error
SetDeadline(time.Time) error
SetReadDeadline(time.Time) error
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 ¶
CountConnections counts the number of currently active connections and returns it.
func (Engine) Dup ¶
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 ¶
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 ¶
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.
type EventHandler ¶
type EventHandler interface {
OnBoot(eng Engine) (action Action)
OnShutdown(eng Engine)
OnOpen(c Conn) (out []byte, action Action)
OnClose(c Conn, err error) (action Action)
OnTraffic(c Conn) (action Action)
OnTick() (delay time.Duration, action Action)
}
EventHandler represents the engine events' callbacks for the Run call.
type EventLoop ¶
type EventLoop interface {
Register(ctx context.Context, addr net.Addr) (<-chan RegisteredResult, error)
Enroll(ctx context.Context, c net.Conn) (<-chan RegisteredResult, error)
Execute(ctx context.Context, runnable Runnable) error
Schedule(ctx context.Context, runnable Runnable, delay time.Duration) error
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 ¶
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 ¶
WithEdgeTriggeredIO enables the edge-triggered I/O for the underlying epoll/kqueue event-loop.
func WithEdgeTriggeredIOChunk ¶
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 ¶
WithLockOSThread enables LockOSThread mode for I/O event-loops.
func WithLogLevel ¶
WithLogLevel specifies the logging level for the local logging file.
func WithLogPath ¶
WithLogPath specifies a local path for logging file.
func WithLogger ¶
WithLogger specifies a customized logger.
func WithMulticastInterfaceIndex ¶
WithMulticastInterfaceIndex sets the interface name where UDP multicast sockets will be bound to.
func WithMulticore ¶
WithMulticore enables multi-cores mode for gnet engine.
func WithNumEventLoop ¶
WithNumEventLoop sets the number of event loops for gnet engine.
func WithReadBufferCap ¶
WithReadBufferCap sets ReadBufferCap for reading bytes.
func WithReuseAddr ¶
WithReuseAddr sets SO_REUSEADDR socket option.
func WithReusePort ¶
WithReusePort sets SO_REUSEPORT socket option.
func WithSocketRecvBuffer ¶
WithSocketRecvBuffer sets the maximum socket receive buffer of kernel in bytes.
func WithSocketSendBuffer ¶
WithSocketSendBuffer sets the maximum socket send buffer of kernel in bytes.
func WithTCPKeepAlive ¶
WithTCPKeepAlive enables the TCP keep-alive mechanism and sets its values.
func WithTCPKeepCount ¶
WithTCPKeepCount sets the number of keep-alive probes that will be sent before the connection is considered dead and dropped.
func WithTCPKeepInterval ¶
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 ¶
WithTicker indicates whether a ticker is currently set.
func WithWriteBufferCap ¶
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 ¶
RegisteredResult is the result of a Register call.
type RunnableFunc ¶
RunnableFunc is an adapter to allow the use of ordinary function as a Runnable.
type Socket ¶
type Socket interface {
Fd() int
Dup() (int, error)
SetReadBuffer(size int) error
SetWriteBuffer(size int) error
SetLinger(secs int) error
SetKeepAlivePeriod(d time.Duration) error
SetKeepAlive(enabled bool, idle, intvl time.Duration, cnt int) error
SetNoDelay(noDelay bool) error
}
Socket is a set of functions which manipulate the underlying file descriptor of a connection.
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.
SendTo(buf []byte, addr net.Addr) (n int, err error)
// Writev writes multiple byte slices to remote synchronously, it's not concurrency-safe.
Writev(bs [][]byte) (n int, err error)
// Flush writes any buffered data to the underlying connection, it's not concurrency-safe.
Flush() error
// OutboundBuffered returns the number of bytes that can be read from the current buffer.
OutboundBuffered() int
// AsyncWrite writes bytes to remote asynchronously, it's concurrency-safe.
AsyncWrite(buf []byte, callback AsyncCallback) (err error)
// AsyncWritev writes multiple byte slices to remote asynchronously.
AsyncWritev(bs [][]byte, callback AsyncCallback) (err error)
}
Writer is an interface that consists of a number of methods for writing that Conn must implement.
Source Files
¶
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. |






