gnet package - github.com/panjf2000/gnet/v2 - Go Packages
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.
- 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
This section is empty.
MaxStreamBufferCap is the default buffer size for each stream-oriented connection(TCP/Unix).
FromContext retrieves context value of the Conn stored in ctx, if any.
FromNetAddrContext retrieves the net.Addr value from ctx, if any.
FromNetConnContext retrieves the net.Conn value from ctx, if any.
NewContext returns a new context.Context that carries the value that will be attached to the Conn.
NewNetAddrContext returns a new context.Context that carries the net.Addr value.
NewNetConnContext returns a new context.Context that carries the net.Conn value.
Rotate is like Run but accepts multiple network addresses.
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.
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.
Action is an action that occurs after the completion of an event.
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 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(_ Engine) (action Action)
OnBoot fires when the engine is ready for accepting connections. The parameter engine has information and various utilities.
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(_ 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(_ Engine)
OnShutdown fires when the engine is being shut down, it is called right after all event-loops and connections are closed.
OnTick fires immediately after the engine starts and will fire again following the duration specified by the delay return value.
func (*BuiltinEventEngine) OnTraffic(_ Conn) (action Action)
OnTraffic fires when a local socket receives data from the remote.
Client of gnet.
func NewClient(eh EventHandler, opts ...Option) (cli *Client, err error)
NewClient creates an instance of Client.
DialContext is like Dial but also accepts an empty interface ctx that can be obtained later via Conn.Context.
Enroll converts a net.Conn to gnet.Conn and then adds it into the Client.
EnrollContext is like Enroll but also accepts an empty interface ctx that can be obtained later via Conn.Context.
Start starts the client event-loop, handing IO events.
Stop stops the client event-loop.
Conn is an interface of underlying connection.
Engine represents an engine context which provides some functions.
CountConnections counts the number of currently active connections and returns it.
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.
DupListener is like Dup, but it duplicates the listener with the given network and address. This is useful when there are multiple listeners.
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.
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.
Validate checks whether the engine is available.
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. Each event has an Action return value that is used manage the state of the connection and engine.
EventLoop provides a set of methods for manipulating the event-loop.
LoadBalancing represents the type of load-balancing algorithm.
const ( RoundRobin LoadBalancing = iota LeastConnections SourceAddrHash )
type Option func(opts *Options)
Option is a function that will set up 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.
WithEdgeTriggeredIO enables the edge-triggered I/O for the underlying epoll/kqueue event-loop.
WithEdgeTriggeredIOChunk sets the number of bytes that `gnet` can read/write up to in one event loop of ET.
func WithLoadBalancing(lb LoadBalancing) Option
WithLoadBalancing picks the load-balancing algorithm for gnet engine.
WithLockOSThread enables LockOSThread mode for I/O event-loops.
WithLogLevel specifies the logging level for the local logging file.
WithLogger specifies a customized logger.
WithMulticastInterfaceIndex sets the interface name where UDP multicast sockets will be bound to.
WithNumEventLoop sets the number of event loops for gnet engine.
WithReadBufferCap sets ReadBufferCap for reading bytes.
WithSocketRecvBuffer sets the maximum socket receive buffer of kernel in bytes.
WithSocketSendBuffer sets the maximum socket send buffer of kernel in bytes.
WithTCPKeepAlive enables the TCP keep-alive mechanism and sets its values.
WithTCPKeepCount sets the number of keep-alive probes that will be sent before the connection is considered dead and dropped.
WithTCPKeepInterval sets the interval between TCP keep-alive probes.
func WithTCPNoDelay(tcpNoDelay TCPSocketOpt) Option
WithTCPNoDelay enable/disable the TCP_NODELAY socket option.
Options are configurations for the gnet application.
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.
RegisteredResult is the result of a Register call.
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.
RunnableFunc is an adapter to allow the use of ordinary function as a Runnable.
Run executes the RunnableFunc itself.
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.
TCPSocketOpt is the type of TCP socket options.
const ( TCPNoDelay TCPSocketOpt = iota TCPDelay )
Available TCP socket options.
Writer is an interface that consists of a number of methods for writing that Conn must implement.