gnet

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2023 License: MIT Imports: 24 Imported by: 2

README

1.异步write输出,减少write对loop的占用,减少内存占用

2.修改了buffer实现

3.增加了tls的支持

4.运行单个监听实例下,实现linux平滑重启 -reload,关闭 -stop

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(c gnet.Conn) (out []byte, action gnet.Action) {
	out = c.Read()
	c.ResetBuffer()
	return
}

func main() {
	echo := new(echoServer)
	log.Fatal(gnet.Serve(echo, "tcp://:9000", gnet.WithMulticore(true)))
}

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrInvalidFixedLength invalid fixed length.
	ErrInvalidFixedLength = errors.New("invalid fixed length of bytes")
	// ErrUnexpectedEOF no enough data to read.
	ErrUnexpectedEOF = errors.New("there is no enough data")
	// ErrDelimiterNotFound no such a delimiter.
	ErrDelimiterNotFound = errors.New("there is no such a delimiter")
	// ErrCRLFNotFound CRLF not found.
	ErrCRLFNotFound = errors.New("there is no CRLF")
	// ErrUnsupportedLength unsupported lengthFieldLength.
	ErrUnsupportedLength = errors.New("unsupported lengthFieldLength. (expected: 1, 2, 3, 4, or 8)")
	// ErrTooLessLength adjusted frame length is less than zero.
	ErrTooLessLength = errors.New("adjusted frame length is less than zero")
)
View Source
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 Action

type Action int

Action is an action that occurs after the completion of an event.

const (
	// None indicates that no action should occur following an event.
	None Action = iota

	// Close closes the connection.
	Close

	// Shutdown shutdowns the server.
	Shutdown
)

type AsyncCallback added in v1.3.9

type AsyncCallback func(c Conn) error

type BuiltInFrameCodec

type BuiltInFrameCodec struct {
}

BuiltInFrameCodec is the built-in codec which will be assigned to gnet server when customized codec is not set up.

func (*BuiltInFrameCodec) Decode

func (cc *BuiltInFrameCodec) Decode(c Conn) ([]byte, error)

Decode ...

func (*BuiltInFrameCodec) Encode

func (cc *BuiltInFrameCodec) Encode(c Conn, buf []byte) ([]byte, error)

Encode ...

type ClientManage added in v1.3.3

type ClientManage struct {
	// contains filtered or unexported fields
}

func Client

func Client(eventHandler EventHandler, opts ...Option) *ClientManage

func (*ClientManage) Dial added in v1.3.3

func (srv *ClientManage) Dial(network, addr string) (Conn, error)

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() []byte

	// ResetBuffer resets the inbound ring-buffer, which means all data in the inbound ring-buffer has been evicted.
	ResetBuffer()

	// ShiftN shifts "read" pointer in buffer with the given length.
	ShiftN(n int) (size int)

	// ReadN reads bytes with the given length from inbound ring-buffer and event-loop-buffer, it would move
	// "read" pointer, which means it will evict the data from buffer and it can't be revoked (put back to buffer),
	// 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
	// function 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)

	// 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() error

	UpgradeTls(config *tls.Config) error

	WriteNoCodec(buf []byte) error

	//阻塞并等待所有缓冲区输出,与AsyncWrite相反
	FlushWrite(buf []byte, noCodec ...bool)
}

Conn is a interface of gnet connection.

type EventHandler

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) (action Action)
	//React1(frame []byte, c Conn)(data []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)

	//linux下的平滑重启,要求尽快关闭掉conn,收到请求后请主动关闭长连接,必须在关闭掉所有长连接后,程序才会退出
	SignalClose(c Conn)
}

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

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

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

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

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

func (es *EventServer) PreWrite()

PreWrite fires just before any data is written to any client socket.

func (*EventServer) React

func (es *EventServer) React(frame []byte, c Conn) (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.

func (*EventServer) SignalClose added in v1.3.16

func (es *EventServer) SignalClose(c Conn)

func (*EventServer) Tick

func (es *EventServer) Tick() (delay time.Duration, action Action)

Tick fires immediately after the server starts and will fire again following the duration specified by the delay return value.

type ICodec

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

type IEventLoopGroup interface {
	// contains filtered or unexported methods
}

IEventLoopGroup represents a set of event-loops.

type Option

type Option func(opts *Options)

Option is a function that will set up option.

func WithBlock added in v1.1.1

func WithBlock(block bool) Option

设置为阻塞式

func WithCodec

func WithCodec(codec ICodec) Option

WithCodec sets up a codec to handle TCP stream.

func WithGraceful added in v1.4.0

func WithGraceful(graceful bool) Option

func WithLoopNum added in v1.1.8

func WithLoopNum(n int) Option

WithMulticore sets up multi-cores with gnet.

func WithOptions

func WithOptions(options Options) Option

WithOptions sets up all options.

func WithPidName added in v1.4.0

func WithPidName(name string) Option

func WithReusePort

func WithReusePort(reusePort bool) Option

WithReusePort sets up SO_REUSEPORT socket option.

func WithTCPKeepAlive

func WithTCPKeepAlive(tcpKeepAlive time.Duration) Option

WithTCPKeepAlive sets up SO_KEEPALIVE socket option.

func WithTCPNoDelay added in v1.3.3

func WithTCPNoDelay(b bool) Option

func WithTicker

func WithTicker(ticker bool) Option

WithTicker indicates that a ticker is set.

func WithTls added in v1.1.4

func WithTls(tlsconfig *tls.Config) Option

开启tls模式

func WithWriteTimeOut added in v1.3.12

func WithWriteTimeOut(i int) Option

单位秒

type Options

type Options struct {

	//0 will be runtime.NumCPU().
	LoopNum 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

	Isblock bool

	Tlsconfig *tls.Config

	TCPNoDelay bool

	WriteTimeOut int

	PidName string

	Graceful bool
}

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 an array of listening addresses that align
	// with the addr strings passed to the Serve function.
	Addr net.Addr

	// NumLoops is the number of 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

	// Close the server 在OnInitComplete会把server传递下去,建议在OnInitComplete里面把Server赋值到你的server结构体里,以调用关闭gnet的Close方法
	Close func()
}

Server represents a server context which provides information about the running server and has control functions for managing state.

Directories

Path Synopsis
internal
io
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.
pool
tls module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL