Documentation
¶
Overview ¶
gnet is an event-driven networking framework that is fast and small. It makes direct epoll and kqueue syscalls rather than using the standard Go net package, and works in a similar manner as netty and libuv.
The goal of this project is to create a server framework for Go that performs on par with Redis and Haproxy for packet handling.
gnet sells itself as a high-performance, lightweight, non-blocking, event-driven networking framework written in pure Go which works on transport layer with TCP/UDP/Unix-Socket protocols, so it allows developers to implement their own protocols of application layer upon gnet for building diversified network applications, for instance, you get an HTTP Server or Web Framework if you implement HTTP protocol upon gnet while you have a Redis Server done with the implementation of Redis protocol upon gnet and so on.
Echo server built upon gnet is shown below:
package main import ( "log" "github.com/panjf2000/gnet" ) type echoServer struct { *gnet.EventServer } func (es *echoServer) React(frame []byte, c gnet.Conn) (out []byte, action gnet.Action) { out = frame return } func main() { echo := new(echoServer) log.Fatal(gnet.Serve(echo, "tcp://:9000", gnet.WithMulticore(true))) }
Index ¶
- Variables
- func Serve(eventHandler EventHandler, addr string, opts ...Option) error
- type Action
- type BuiltInFrameCodec
- type Conn
- type DecoderConfig
- type DelimiterBasedFrameCodec
- type EncoderConfig
- type EventHandler
- type EventServer
- 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) PreWrite()
- func (es *EventServer) React(frame []byte, c Conn) (out []byte, action Action)
- func (es *EventServer) Tick() (delay time.Duration, action Action)
- type FixedLengthFrameCodec
- type ICodec
- type IEventLoopGroup
- type LengthFieldBasedFrameCodec
- type LineBasedFrameCodec
- type Logger
- type Option
- func WithCodec(codec ICodec) Option
- func WithLogger(logger Logger) Option
- func WithMulticore(multicore bool) Option
- func WithNumEventLoop(numEventLoop int) Option
- func WithOptions(options Options) Option
- func WithReusePort(reusePort bool) Option
- func WithTCPKeepAlive(tcpKeepAlive time.Duration) Option
- func WithTicker(ticker bool) Option
- type Options
- type Server
Constants ¶
This section is empty.
Variables ¶
var ( // ErrProtocolNotSupported occurs when trying to use protocol that is not supported. ErrProtocolNotSupported = errors.New("not supported protocol on this platform") // ErrServerShutdown occurs when server is closing. ErrServerShutdown = errors.New("server is going to be shutdown") // ErrInvalidFixedLength occurs when the output data have invalid fixed length. ErrInvalidFixedLength = errors.New("invalid fixed length of bytes") // ErrUnexpectedEOF occurs when no enough data to read by codec. ErrUnexpectedEOF = errors.New("there is no enough data") // ErrDelimiterNotFound occurs when no such a delimiter is in input data. ErrDelimiterNotFound = errors.New("there is no such a delimiter") // ErrCRLFNotFound occurs when a CRLF is not found by codec. ErrCRLFNotFound = errors.New("there is no CRLF") // ErrUnsupportedLength occurs when unsupported lengthFieldLength is from input data. ErrUnsupportedLength = errors.New("unsupported lengthFieldLength. (expected: 1, 2, 3, 4, or 8)") // ErrTooLessLength occurs when adjusted frame length is less than zero. ErrTooLessLength = errors.New("adjusted frame length is less than zero") )
var CRLFByte = byte('\n')
CRLFByte represents a byte of CRLF.
Functions ¶
func Serve ¶
func Serve(eventHandler EventHandler, addr string, opts ...Option) error
Serve starts handling events for the specified addresses.
Addresses 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 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 and event-loop-buffer without moving "read" pointer, which means // it does not evict the data from ring-buffer actually and those data will present in ring-buffer until the // ResetBuffer method is invoked. Read() (buf []byte) // ResetBuffer resets the inbound ring-buffer, which means all data in the inbound ring-buffer has been evicted. ResetBuffer() // ReadN reads bytes with the given length from inbound ring-buffer and event-loop-buffer without moving // "read" pointer, which means it will not evict the data from buffer until the ShiftN method is invoked, // it reads data from the inbound ring-buffer and event-loop-buffer when the length of the available data is equal // to the given "n", otherwise, it will not read any data from the inbound ring-buffer. // // So you should use this method only if you know exactly the length of subsequent TCP stream based on the protocol, // like the Content-Length attribute in an HTTP request which indicates you how much data you should read // from inbound ring-buffer. ReadN(n int) (size int, buf []byte) // ShiftN shifts "read" pointer in buffer with the given length. ShiftN(n int) (size int) // BufferLength returns the length of available data in the inbound ring-buffer. 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 data to client/connection asynchronously, usually you would invoke it in individual goroutines // instead of the event-loop goroutines. AsyncWrite(buf []byte) error // Wake triggers a React event for this connection. Wake() error // Close closes the current connection. Close() error }
Conn is a 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 server parameter has information and various utilities. OnInitComplete(server Server) (action Action) // OnOpened fires when a new connection has been opened. // The info parameter has information about the connection such as // it's local and remote address. // Use the out return value to write data to the connection. OnOpened(c Conn) (out []byte, action Action) // OnClosed fires when a connection has been closed. // The err parameter is the last known connection error. OnClosed(c Conn, err error) (action Action) // PreWrite fires just before any data is written to any client socket. PreWrite() // React fires when a connection sends the server data. // Invoke c.Read() or c.ReadN(n) within the parameter c to read incoming data from client/connection. // Use the out return value to write data to the client/connection. React(frame []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) 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 err parameter 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 server parameter 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 info parameter has information about the connection such as it's local and remote address. Use the out return value to write data to the connection.
func (*EventServer) PreWrite ¶ added in v1.0.0
func (es *EventServer) PreWrite()
PreWrite fires just before any data is written to any client socket.
func (*EventServer) React ¶ added in v1.0.0
func (es *EventServer) React(frame []byte, c Conn) (out []byte, action Action)
React fires when a connection sends the server data. Invoke c.Read() or c.ReadN(n) within the parameter c to read incoming data from client/connection. Use the out return value to write data to the client/connection.
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. Decode(c Conn) ([]byte, error) }
ICodec is the interface of gnet codec.
type IEventLoopGroup ¶ added in v1.0.0
type IEventLoopGroup interface {
// contains filtered or unexported methods
}
IEventLoopGroup represents a set of event-loops.
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. Original implementation: https://github.com/netty/netty/blob/4.1/codec/src/main/java/io/netty/handler/codec/LengthFieldBasedFrameDecoder.java
func NewLengthFieldBasedFrameCodec ¶ added in v1.0.0
func NewLengthFieldBasedFrameCodec(encoderConfig EncoderConfig, decoderConfig 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 Logger ¶ added in v1.0.0
type Logger interface { // Printf must have the same semantics as log.Printf. Printf(format string, args ...interface{}) }
Logger is used for logging formatted messages.
type Option ¶ added in v1.0.0
type Option func(opts *Options)
Option is a function that will set up option.
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 WithReusePort ¶ added in v1.0.0
WithReusePort sets up SO_REUSEPORT socket option.
func WithTCPKeepAlive ¶ added in v1.0.0
WithTCPKeepAlive sets up SO_KEEPALIVE 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 runtime.NumCPU(). Multicore bool // NumEventLoop is set up to start the given number of event-loop goroutine. // Note: Setting up NumEventLoop will override Multicore. NumEventLoop int // ReusePort indicates whether to set up the SO_REUSEPORT socket option. ReusePort bool // Ticker indicates whether the ticker has been set up. Ticker bool // TCPKeepAlive (SO_KEEPALIVE) socket option. TCPKeepAlive time.Duration // ICodec encodes and decodes TCP stream. Codec ICodec // Logger is the customized logger for logging info, if it is not set, default standard logger from log package is used. Logger Logger }
Options are set when the client opens.
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 runtime.NumCPU(). Multicore bool // The Addr parameter 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 }
Server represents a server context which provides information about the running server and has control functions for managing state.