Documentation ¶
Index ¶
- Variables
- 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 interface{}) (Conn, error)
- func (cli *Client) Enroll(c net.Conn) (Conn, error)
- func (cli *Client) EnrollContext(c net.Conn, ctx interface{}) (Conn, error)
- func (cli *Client) Start() error
- func (cli *Client) Stop() (err error)
- type Conn
- type Engine
- type EventHandler
- type LoadBalancing
- type Option
- func WithEdgeTriggeredIO(et bool) 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 WithTCPNoDelay(tcpNoDelay TCPSocketOpt) Option
- func WithTicker(ticker bool) Option
- func WithWriteBufferCap(writeBufferCap int) Option
- type Options
- type Reader
- 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 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
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 AsyncCallback ¶
AsyncCallback is a callback which will be invoked after the asynchronous functions has finished executing.
Note that the parameter gnet.Conn is already released under UDP protocol, thus it's not allowed to be accessed.
type BuiltinEventEngine ¶
type BuiltinEventEngine struct{}
BuiltinEventEngine is a built-in implementation of EventHandler which sets up each method with a default implementation, you can compose it with your own implementation of EventHandler when you don't want to implement all methods in 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) DialContext ¶ added in v2.4.0
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
Enroll converts a net.Conn to gnet.Conn and then adds it into Client.
func (*Client) EnrollContext ¶ added in v2.4.0
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 // 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 interface{}) // SetContext sets a user-defined context, it's not concurrency-safe, // you must invoke it within any method in EventHandler. SetContext(ctx interface{}) // LocalAddr is the connection's local socket address, it's not concurrency-safe, // you must invoke it within any method in EventHandler. LocalAddr() (addr net.Addr) // RemoteAddr is the connection's remote address, it's not concurrency-safe, // you must invoke it within any method in EventHandler. RemoteAddr() (addr net.Addr) // Wake triggers a OnTraffic event for the current connection, it's concurrency-safe. Wake(callback AsyncCallback) (err 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) (err error) // Close closes the current connection, implements net.Conn, it's concurrency-safe. Close() (err error) // SetDeadline implements net.Conn. SetDeadline(t time.Time) (err error) // SetReadDeadline implements net.Conn. SetReadDeadline(t time.Time) (err error) // SetWriteDeadline implements net.Conn. SetWriteDeadline(t time.Time) (err 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.
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. // // Note that the []byte returned from Conn.Peek(int)/Conn.Next(int) is not allowed to be passed to a new goroutine, // as this []byte will be reused within event-loop after OnTraffic() returns. // If you have to use this []byte in a new goroutine, you should either make a copy of it or call Conn.Read([]byte) // to read data into your own []byte, then pass the new []byte to the new goroutine. 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 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 WithEdgeTriggeredIO ¶ added in v2.5.0
WithEdgeTriggeredIO enables the edge-triggered I/O for the underlying epoll/kqueue event-loop.
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 ¶ added in v2.2.0
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 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 { // 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 // LB represents the load-balancing algorithm used when assigning new connections // to event loops. LB LoadBalancing // ReuseAddr indicates whether to set the SO_REUSEADDR socket option. ReuseAddr bool // ReusePort indicates whether to set the SO_REUSEPORT socket option. ReusePort bool // MulticastInterfaceIndex is the index of the interface name where the multicast UDP addresses will be bound to. MulticastInterfaceIndex 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 enable the TCP keep-alive mechanism (SO_KEEPALIVE) and set its value // on TCP_KEEPIDLE, 1/5 of its value on TCP_KEEPINTVL, and 5 on TCP_KEEPCNT. TCPKeepAlive time.Duration // 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 }
Options are configurations for the gnet application.
type Reader ¶
type Reader interface { io.Reader io.WriterTo // Next returns a slice containing the next n bytes from the buffer, // advancing the buffer as if the bytes had been returned by Read. // Calling this method has the same effect as calling Peek and Discard. // If the amount of the available bytes is less than requested, a pair of (0, io.ErrShortBuffer) // is returned. // // Note that the []byte buf returned by Next() is not allowed to be passed to a new goroutine, // as this []byte will be reused within event-loop. // If you have to use buf in a new goroutine, then you need to make a copy of buf and pass this copy // to that new goroutine. 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. If the amount of the available bytes is // less than requested, a pair of (0, io.ErrShortBuffer) is returned. // // Note that the []byte buf returned by Peek() is not allowed to be passed to a new goroutine, // as this []byte will be reused within event-loop. // If you have to use buf in a new goroutine, then you need to make a copy of buf and pass this copy // to that new goroutine. 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() (n 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 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's. Attempting to change 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(bytes int) error // SetWriteBuffer sets the size of the operating system's // transmit buffer associated with the connection. SetWriteBuffer(bytes int) error // SetLinger sets the behavior of Close on a connection which still // has data waiting to be sent or to be acknowledged. // // If sec < 0 (the default), the operating system finishes sending the // data in the background. // // If sec == 0, the operating system discards any unsent or // unacknowledged data. // // If sec > 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(sec int) error // SetKeepAlivePeriod tells operating system to send keep-alive messages on the connection // and sets period between TCP keep-alive probes. SetKeepAlivePeriod(d time.Duration) 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 // 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() (err 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() (n 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.
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. |
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 functions that return fd and net.Addr based on given the protocol and address with a SO_REUSEPORT option set to the socket.
|
Package socket provides functions that return fd and net.Addr based on given the protocol and address with a SO_REUSEPORT option set to the socket. |
pkg
|
|
logging
Package logging provides logging functionality for gnet server, it sets up a default logger (powered by go.uber.org/zap) which is about to be used by gnet server, it also allows users to replace the default logger with their customized logger by just implementing the `Logger` interface and assign it to the functional option `Options.Logger`, pass it to `gnet.Serve` method.
|
Package logging provides logging functionality for gnet server, it sets up a default logger (powered by go.uber.org/zap) which is about to be used by gnet server, it also allows users to replace the default logger with their customized logger by just implementing the `Logger` interface and assign it to the functional option `Options.Logger`, pass it to `gnet.Serve` method. |