Documentation
¶
Index ¶
- Constants
- Variables
- func Serve(eventHandler EventHandler, protoAddr string, opts ...Option) (err error)
- func Stop(ctx context.Context, protoAddr string) error
- type Action
- type BuiltInFrameCodec
- type Client
- type Conn
- type DecoderConfig
- type DelimiterBasedFrameCodec
- type EncoderConfig
- type EventHandler
- type EventServer
- func (es *EventServer) AfterWrite(c Conn, b []byte)
- func (es *EventServer) OnClosed(c Conn, err error) (action Action)
- func (es *EventServer) OnInitComplete(svr Server) (action Action)
- func (es *EventServer) OnOpened(c Conn) (out []byte, action Action)
- func (es *EventServer) OnShutdown(svr Server)
- func (es *EventServer) PreWrite(c Conn)
- func (es *EventServer) React(packet []byte, c Conn) (out []byte, action Action)
- func (es *EventServer) Tick() (delay time.Duration, action Action)
- type FixedLengthFrameCodec
- type ICodec
- type LengthFieldBasedFrameCodec
- type LineBasedFrameCodec
- type LoadBalancing
- type Option
- func WithCodec(codec ICodec) 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 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
- type Options
- type Server
- type TCPSocketOpt
Constants ¶
const ( // MaxBytesToWritePerLoop is the maximum amount of bytes to be sent in one system call. MaxBytesToWritePerLoop = 64 * 1024 // MaxIovSize is IOV_MAX. MaxIovSize = 1024 )
Variables ¶
var CRLFByte = byte('\n')
CRLFByte represents a byte of CRLF.
Functions ¶
func Serve ¶
func Serve(eventHandler EventHandler, protoAddr string, opts ...Option) (err error)
Serve starts handling events for 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.
Types ¶
type BuiltInFrameCodec ¶ added in v1.0.0
type BuiltInFrameCodec struct{}
BuiltInFrameCodec is the built-in codec which will be assigned to gnet server when customized codec is not set up.
type Client ¶ added in v1.6.0
type Client struct {
// contains filtered or unexported fields
}
Client of gnet.
func NewClient ¶ added in v1.6.0
func NewClient(eventHandler EventHandler, opts ...Option) (cli *Client, err error)
NewClient creates an instance of Client.
type Conn ¶
type Conn interface {
// Context returns a user-defined context.
Context() (ctx interface{})
// SetContext sets a user-defined context.
SetContext(ctx interface{})
// LocalAddr is the connection's local socket address.
LocalAddr() (addr net.Addr)
// RemoteAddr is the connection's remote peer address.
RemoteAddr() (addr net.Addr)
// Read reads all data from inbound ring-buffer without moving "read" pointer,
// which means it does not evict the data from buffers actually and those data will
// present in buffers until the ResetBuffer method is called.
//
// Note that the (buf []byte) returned by Read() 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.
Read() (buf []byte)
// ResetBuffer resets the buffers, which means all data in inbound ring-buffer and event-loop-buffer will be evicted.
ResetBuffer()
// ReadN reads bytes with the given length from inbound ring-buffer without moving "read" pointer,
// which means it will not evict the data from buffers until the ShiftN method is called,
// it reads data from the inbound ring-buffer and returns both bytes and the size of it.
// If the length of the available data is less than the given "n", ReadN will return all available data,
// so you should make use of the variable "size" returned by ReadN() to be aware of the exact length of the returned data.
//
// Note that the []byte buf returned by ReadN() 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.
ReadN(n int) (size int, buf []byte)
// ShiftN shifts "read" pointer in the internal buffers with the given length.
ShiftN(n int) (size int)
// BufferLength returns the length of available data in the internal buffers.
BufferLength() (size int)
// SendTo writes data for UDP sockets, it allows you to send data back to UDP socket in individual goroutines.
SendTo(buf []byte) error
// AsyncWrite writes one byte slice to peer asynchronously, usually you would call it in individual goroutines
// instead of the event-loop goroutines.
AsyncWrite(buf []byte) error
// AsyncWritev writes multiple byte slices to peer asynchronously, usually you would call it in individual goroutines
// instead of the event-loop goroutines.
AsyncWritev(bs [][]byte) error
// Wake triggers a React event for the connection.
Wake() error
// Close closes the current connection.
Close() error
}
Conn is an interface of gnet connection.
type DecoderConfig ¶ added in v1.0.0
type DecoderConfig struct {
// ByteOrder is the ByteOrder of the length field.
ByteOrder binary.ByteOrder
// LengthFieldOffset is the offset of the length field
LengthFieldOffset int
// LengthFieldLength is the length of the length field
LengthFieldLength int
// LengthAdjustment is the compensation value to add to the value of the length field
LengthAdjustment int
// InitialBytesToStrip is the number of first bytes to strip out from the decoded frame
InitialBytesToStrip int
}
DecoderConfig config for decoder.
type DelimiterBasedFrameCodec ¶ added in v1.0.0
type DelimiterBasedFrameCodec struct {
// contains filtered or unexported fields
}
DelimiterBasedFrameCodec encodes/decodes specific-delimiter-separated frames into/from TCP stream.
func NewDelimiterBasedFrameCodec ¶ added in v1.0.0
func NewDelimiterBasedFrameCodec(delimiter byte) *DelimiterBasedFrameCodec
NewDelimiterBasedFrameCodec instantiates and returns a codec with a specific delimiter.
type EncoderConfig ¶ added in v1.0.0
type EncoderConfig struct {
// ByteOrder is the ByteOrder of the length field.
ByteOrder binary.ByteOrder
// LengthFieldLength is the length of the length field.
LengthFieldLength int
// LengthAdjustment is the compensation value to add to the value of the length field
LengthAdjustment int
// LengthIncludesLengthFieldLength is true, the length of the prepended length field is added to the value of
// the prepended length field
LengthIncludesLengthFieldLength bool
}
EncoderConfig config for encoder.
type EventHandler ¶ added in v1.0.0
type EventHandler interface {
// OnInitComplete fires when the server is ready for accepting connections.
// The parameter server has information and various utilities.
OnInitComplete(server Server) (action Action)
// OnShutdown fires when the server is being shut down, it is called right after
// all event-loops and connections are closed.
OnShutdown(server Server)
// OnOpened fires when a new connection has been opened.
// The Conn c has information about the connection such as it's local and remote address.
// The parameter out is the return value which is going to be sent back to the peer.
// It is usually not recommended to send large amounts of data back to the peer in OnOpened.
//
// Note that the bytes returned by OnOpened will be sent back to the peer without being encoded.
OnOpened(c Conn) (out []byte, action Action)
// OnClosed fires when a connection has been closed.
// The parameter err is the last known connection error.
OnClosed(c Conn, err error) (action Action)
// PreWrite fires just before a packet is written to the peer socket, this event function is usually where
// you put some code of logging/counting/reporting or any fore operations before writing data to the peer.
PreWrite(c Conn)
// AfterWrite fires right after a packet is written to the peer socket, this event function is usually where
// you put the []byte returned from React() back to your memory pool.
AfterWrite(c Conn, b []byte)
// React fires when a socket receives data from the peer.
// Call c.Read() or c.ReadN(n) of Conn c to read incoming data from the peer.
// The parameter out is the return value which is going to be sent back to the peer.
//
// Note that the parameter packet returned from React() is not allowed to be passed to a new goroutine,
// as this []byte will be reused within event-loop after React() returns.
// If you have to use packet in a new goroutine, then you need to make a copy of buf and pass this copy
// to that new goroutine.
React(packet []byte, c Conn) (out []byte, action Action)
// Tick fires immediately after the server starts and will fire again
// following the duration specified by the delay return value.
Tick() (delay time.Duration, action Action)
}
EventHandler represents the server events' callbacks for the Serve call. Each event has an Action return value that is used manage the state of the connection and server.
type EventServer ¶ added in v1.0.0
type EventServer struct{}
EventServer 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 (*EventServer) AfterWrite ¶ added in v1.6.0
func (es *EventServer) AfterWrite(c Conn, b []byte)
AfterWrite fires right after a packet is written to the peer socket, this event function is usually where you put the []byte's back to your memory pool.
func (*EventServer) OnClosed ¶ added in v1.0.0
func (es *EventServer) OnClosed(c Conn, err error) (action Action)
OnClosed fires when a connection has been closed. The parameter err is the last known connection error.
func (*EventServer) OnInitComplete ¶ added in v1.0.0
func (es *EventServer) OnInitComplete(svr Server) (action Action)
OnInitComplete fires when the server is ready for accepting connections. The parameter server has information and various utilities.
func (*EventServer) OnOpened ¶ added in v1.0.0
func (es *EventServer) OnOpened(c Conn) (out []byte, action Action)
OnOpened fires when a new connection has been opened. The parameter out is the return value which is going to be sent back to the peer.
func (*EventServer) OnShutdown ¶ added in v1.2.0
func (es *EventServer) OnShutdown(svr Server)
OnShutdown fires when the server is being shut down, it is called right after all event-loops and connections are closed.
func (*EventServer) PreWrite ¶ added in v1.0.0
func (es *EventServer) PreWrite(c Conn)
PreWrite fires just before a packet is written to the peer socket, this event function is usually where you put some code of logging/counting/reporting or any fore operations before writing data to the peer.
func (*EventServer) React ¶ added in v1.0.0
func (es *EventServer) React(packet []byte, c Conn) (out []byte, action Action)
React fires when a connection sends the server data. Call c.Read() or c.ReadN(n) of Conn c to read incoming data from the peer. The parameter out is the return value which is going to be sent back to the peer.
type FixedLengthFrameCodec ¶ added in v1.0.0
type FixedLengthFrameCodec struct {
// contains filtered or unexported fields
}
FixedLengthFrameCodec encodes/decodes fixed-length-separated frames into/from TCP stream.
func NewFixedLengthFrameCodec ¶ added in v1.0.0
func NewFixedLengthFrameCodec(frameLength int) *FixedLengthFrameCodec
NewFixedLengthFrameCodec instantiates and returns a codec with fixed length.
type ICodec ¶ added in v1.0.0
type ICodec interface {
// Encode encodes frames upon server responses into TCP stream.
Encode(c Conn, buf []byte) ([]byte, error)
// Decode decodes frames from TCP stream via specific implementation.
//
// Note that when there is an incomplete packet, you should return (nil, ErrIncompletePacket)
// to make gnet continue reading data from socket, otherwise, any error other than ErrIncompletePacket
// will cause the connection to close.
Decode(c Conn) ([]byte, error)
}
ICodec is the interface of gnet codec.
type LengthFieldBasedFrameCodec ¶ added in v1.0.0
type LengthFieldBasedFrameCodec struct {
// contains filtered or unexported fields
}
LengthFieldBasedFrameCodec is the refactoring from https://github.com/smallnest/goframe/blob/master/length_field_based_frameconn.go, licensed by Apache License 2.0. It encodes/decodes frames into/from TCP stream with value of the length field in the message.
func NewLengthFieldBasedFrameCodec ¶ added in v1.0.0
func NewLengthFieldBasedFrameCodec(ec EncoderConfig, dc DecoderConfig) *LengthFieldBasedFrameCodec
NewLengthFieldBasedFrameCodec instantiates and returns a codec based on the length field. It is the go implementation of netty LengthFieldBasedFrameecoder and LengthFieldPrepender. you can see javadoc of them to learn more details.
type LineBasedFrameCodec ¶ added in v1.0.0
type LineBasedFrameCodec struct{}
LineBasedFrameCodec encodes/decodes line-separated frames into/from TCP stream.
type LoadBalancing ¶ added in v1.1.0
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 ¶ added in v1.0.0
type Option func(opts *Options)
Option is a function that will set up option.
func WithLoadBalancing ¶ added in v1.1.0
func WithLoadBalancing(lb LoadBalancing) Option
WithLoadBalancing sets up the load-balancing algorithm in gnet server.
func WithLockOSThread ¶ added in v1.3.0
WithLockOSThread sets up LockOSThread mode for I/O event-loops.
func WithLogLevel ¶ added in v1.4.6
WithLogLevel is an option to set up the logging level.
func WithLogPath ¶ added in v1.4.6
WithLogPath is an option to set up the local path of log file.
func WithLogger ¶ added in v1.0.0
WithLogger sets up a customized logger.
func WithMulticore ¶ added in v1.0.0
WithMulticore sets up multi-cores in gnet server.
func WithNumEventLoop ¶ added in v1.0.0
WithNumEventLoop sets up NumEventLoop in gnet server.
func WithOptions ¶ added in v1.0.0
WithOptions sets up all options.
func WithReadBufferCap ¶ added in v1.4.1
WithReadBufferCap sets up ReadBufferCap for reading bytes.
func WithReuseAddr ¶ added in v1.6.0
WithReuseAddr sets up SO_REUSEADDR socket option.
func WithReusePort ¶ added in v1.0.0
WithReusePort sets up SO_REUSEPORT socket option.
func WithSocketRecvBuffer ¶ added in v1.4.3
WithSocketRecvBuffer sets the maximum socket receive buffer in bytes.
func WithSocketSendBuffer ¶ added in v1.4.3
WithSocketSendBuffer sets the maximum socket send buffer in bytes.
func WithTCPKeepAlive ¶ added in v1.0.0
WithTCPKeepAlive sets up the SO_KEEPALIVE socket option with duration.
func WithTCPNoDelay ¶ added in v1.4.0
func WithTCPNoDelay(tcpNoDelay TCPSocketOpt) Option
WithTCPNoDelay enable/disable the TCP_NODELAY socket option.
func WithTicker ¶ added in v1.0.0
WithTicker indicates that a ticker is set.
type Options ¶
type Options struct {
// Multicore indicates whether the server 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 server with single thread. The number of threads in the server will be automatically
// assigned to the value of logical CPUs usable by the current process.
Multicore bool
// NumEventLoop is set up to start the given number of event-loop goroutine.
// Note: Setting up NumEventLoop will override Multicore.
NumEventLoop int
// LB represents the load-balancing algorithm used when assigning new connections.
LB LoadBalancing
// ReuseAddr indicates whether to set up the SO_REUSEADDR socket option.
ReuseAddr bool
// ReusePort indicates whether to set up the SO_REUSEPORT socket option.
ReusePort bool
// ReadBufferCap is the maximum number of bytes that can be read from the peer when the readable event comes.
// The default value is 64KB, it can be reduced to avoid starving the subsequent connections.
//
// 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
// LockOSThread is used to determine whether each I/O event-loop is 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 sets up a duration for (SO_KEEPALIVE) socket option.
TCPKeepAlive time.Duration
// TCPNoDelay 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 operation.
TCPNoDelay TCPSocketOpt
// SocketRecvBuffer sets the maximum socket receive buffer in bytes.
SocketRecvBuffer int
// SocketSendBuffer sets the maximum socket send buffer in bytes.
SocketSendBuffer int
// ICodec encodes and decodes TCP stream.
Codec ICodec
// LogPath the 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
// you own logger during the lifetime by implementing the following log.Logger interface.
//
// Note that this option can be overridden by the option Logger.
LogPath string
// LogLevel indicates 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
}
Options are configurations for the gnet application.
type Server ¶
type Server struct {
// Multicore indicates whether the server will be effectively created with multi-cores, if so,
// then you must take care of synchronizing the shared data between all event callbacks, otherwise,
// it will run the server with single thread. The number of threads in the server will be automatically
// assigned to the value of logical CPUs usable by the current process.
Multicore bool
// Addr is the listening address that align
// with the addr string passed to the Serve function.
Addr net.Addr
// NumEventLoop is the number of event-loops that the server is using.
NumEventLoop int
// ReusePort indicates whether SO_REUSEPORT is enable.
ReusePort bool
// TCPKeepAlive (SO_KEEPALIVE) socket option.
TCPKeepAlive time.Duration
// contains filtered or unexported fields
}
Server represents a server context which provides information about the running server and has control functions for managing state.
func (Server) CountConnections ¶ added in v1.1.0
CountConnections counts the number of currently active connections and returns it.
type TCPSocketOpt ¶ added in v1.4.0
type TCPSocketOpt int
TCPSocketOpt is the type of TCP socket options.
const ( TCPNoDelay TCPSocketOpt = iota TCPDelay )
Available TCP socket options.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
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. |












