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.

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.

const (
	
	None Action = iota

	
	Close

	
	Shutdown
)

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.

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

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.

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(et bool) Option

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

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(lb LoadBalancing) Option

WithLoadBalancing picks the load-balancing algorithm for gnet engine.

func WithLockOSThread(lockOSThread bool) Option

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

WithLogLevel specifies the logging level for the local logging file.

func WithLogPath(fileName string) Option

WithLogPath specifies a local path for logging file.

WithLogger specifies a customized logger.

func WithMulticastInterfaceIndex(idx int) Option

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

func WithMulticore(multicore bool) Option

WithMulticore enables multi-cores mode for gnet engine.

func WithNumEventLoop(numEventLoop int) Option

WithNumEventLoop sets the number of event loops for gnet engine.

func WithOptions(options Options) Option

WithOptions sets up all options.

func WithReadBufferCap(readBufferCap int) Option

WithReadBufferCap sets ReadBufferCap for reading bytes.

func WithReuseAddr(reuseAddr bool) Option

WithReuseAddr sets SO_REUSEADDR socket option.

func WithReusePort(reusePort bool) Option

WithReusePort sets SO_REUSEPORT socket option.

func WithSocketRecvBuffer(recvBuf int) Option

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

func WithSocketSendBuffer(sendBuf int) Option

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

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

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.

WithTCPKeepInterval sets the interval between TCP keep-alive probes.

func WithTCPNoDelay(tcpNoDelay TCPSocketOpt) Option

WithTCPNoDelay enable/disable the TCP_NODELAY socket option.

func WithTicker(ticker bool) Option

WithTicker indicates whether a ticker is currently set.

func WithWriteBufferCap(writeBufferCap int) Option

WithWriteBufferCap sets WriteBufferCap for pending bytes.

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.

type RegisteredResult struct {
	Conn Conn
	Err  error
}

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.