nano

package module
v1.1.71 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2023 License: MIT Imports: 22 Imported by: 0

README

Nano Build Status GoDoc Go Report Card MIT licensed

Nano is an easy to use, fast, lightweight game server networking library for Go. It provides a core network architecture and a series of tools and libraries that can help developers eliminate boring duplicate work for common underlying logic. The goal of nano is to improve development efficiency by eliminating the need to spend time on repetitious network related programming.

Nano was designed for server-side applications like real-time games, social games, mobile games, etc of all sizes.

How to build a system with Nano

What does a Nano application look like?

The simplest "nano" application as shown in the following figure, you can make powerful applications by combining different components.

Application

In fact, the nano application is a collection of  Component , and a component is a bundle of  Handler, once you register a component to nano, nano will register all methods that can be converted to Handler to nano service container. Service was accessed by Component.Handler, and the handler will be called while client request. The handler will receive two parameters while handling a message:

  • *session.Session: corresponding a client that apply this request or notify.
  • *protocol.FooBar: the payload of the request.

While you had processed your logic, you can response or push message to the client by session.Response(payload) and session.Push('eventName', payload), or returns error when some unexpected data received.

How to build distributed system with Nano

Nano contains built-in distributed system solution, and make you creating a distributed game server easily.

See: The distributed chat demo

The Nano will remain simple, but you can perform any operations in the component and get the desired goals. You can startup a group of Nano application as agent to dispatch message to backend servers.

How to execute the asynchronous task
func (manager *PlayerManager) Login(s *session.Session, msg *ReqPlayerLogin) error {
    var onDBResult = func(player *Player) {
        manager.players = append(manager.players, player)
        s.Push("PlayerSystem.LoginSuccess", &ResPlayerLogin)
    }
    
    // run slow task in new gorontine
    go func() {
        player, err := db.QueryPlayer(msg.PlayerId) // ignore error in demo
        // handle result in main logical gorontine
        nano.Invoke(func(){ onDBResult(player) })
    }
    return nil
}

Documents

Resources

Community

Successful cases

Go version

> go1.8

Installation

go get github.com/aura-studio/nano

# dependencies
go get -u github.com/golang/protobuf
go get -u github.com/gorilla/websocket

Benchmark

# Case:   PingPong
# OS:     Windows 10
# Device: i5-6500 3.2GHz 4 Core/1000-Concurrent   => IOPS 11W(Average)
# Other:  ...

cd $GOPATH/src/github.com/aura-studio/nano/benchmark/io
go test -v -tags "benchmark"

License

MIT License

Documentation

Index

Constants

View Source
const (
	Cluster   = "cluster"
	Singleton = "singleton"
	Frontend  = "frontend"
	Backend   = "backend"
)

Variables

View Source
var (
	ErrCloseClosedGroup   = errors.New("close closed group")
	ErrClosedGroup        = errors.New("group closed")
	ErrMemberNotFound     = errors.New("member not found in the group")
	ErrSessionDuplication = errors.New("session is already in the current group")
)

Errors that could be occurred during message handling.

Functions

func Close added in v1.1.14

func Close()

Close send a signal to let 'nano' close itself.

func Ready added in v1.0.0

func Ready() <-chan struct{}

func Serve added in v1.0.1

func Serve(opts ...Option)

Serve listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections.

func Stopping added in v1.0.1

func Stopping() bool

Types

type Group

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

Group represents a session group which used to manage a number of sessions, data send to the group will send to all session in it.

func NewGroup

func NewGroup(n string) *Group

NewGroup returns a new group instance

func (*Group) Add

func (c *Group) Add(session *session.Session) error

Add add session to group

func (*Group) Broadcast

func (c *Group) Broadcast(route string, v interface{}) error

Broadcast push the message(s) to all members

func (*Group) Close

func (c *Group) Close() error

Close destroy group, which will release all resource in the group

func (*Group) Contains

func (c *Group) Contains(uid int64) bool

Contains check whether a UID is contained in current group or not

func (*Group) Count

func (c *Group) Count() int

Count get current member amount in the group

func (*Group) Leave

func (c *Group) Leave(s *session.Session) error

Leave remove specified UID related session from group

func (*Group) LeaveAll

func (c *Group) LeaveAll() error

LeaveAll clear all sessions in the group

func (*Group) Member

func (c *Group) Member(uid int64) (*session.Session, error)

Member returns specified UID's session

func (*Group) Members

func (c *Group) Members() []int64

Members returns all member's UID in current group

func (*Group) Multicast

func (c *Group) Multicast(route string, v interface{}, filter SessionFilter) error

Multicast push the message to the filtered clients

type Option

type Option func(*options.Options)

Option defines a type for option, an option is a func operate options.NodeOptions

func WithAdvertiseAddr added in v1.0.0

func WithAdvertiseAddr(addr string, retryInterval ...time.Duration) Option

WithAdvertiseAddr sets the advertise address option, it will be the listen address in master node and an advertise address which cluster member to connect

func WithCodec added in v1.0.1

func WithCodec(c codec.Codec) Option

func WithComponents added in v1.0.0

func WithComponents(components *component.Components) Option

WithComponents sets the Components

func WithDebugAddr added in v1.0.0

func WithDebugAddr(addr string) Option

WithDebugAddr works with debug http addr

func WithDebugMode added in v1.0.0

func WithDebugMode(debug bool) Option

WithDebugMode makes 'nano' run under Debug mode.

func WithEtcd added in v1.1.0

func WithEtcd() Option

func WithGrpcOptions added in v1.0.0

func WithGrpcOptions(opts ...grpc.DialOption) Option

WithGrpcOptions sets the grpc dial options

func WithHttpAddr added in v1.0.0

func WithHttpAddr(httpAddr string) Option

WithHttpAddr sets the independent http address

func WithLabel added in v1.0.0

func WithLabel(label string) Option

WithLabel sets the current node label in cluster

func WithLogger added in v1.0.0

func WithLogger(l log.Logger) Option

WithLogger overrides the default logger

func WithMaster added in v1.0.0

func WithMaster() Option

WithMaster sets the option to indicate whether the current node is master node

func WithMasterPersist added in v1.0.0

func WithMasterPersist(persist persist.Persist) Option

WithMasterPersist sets the persist of cluster

func WithMemberAddr added in v1.0.1

func WithMemberAddr(addr string) Option

func WithPipeline

func WithPipeline(pipeline pipeline.Pipeline) Option

WithPipeline sets the pipeline option.

func WithSafeMode added in v1.0.0

func WithSafeMode(safe bool) Option

WithSafeMode makes 'nano' run under Safe mode.

func WithTCPAddr added in v1.0.1

func WithTCPAddr(addr string) Option

WithTCPAddr sets the listen address which is used to establish connection between cluster members. Will select an available port automatically if no member address setting and panic if no available port

func WithTSLConfig added in v1.0.0

func WithTSLConfig(certificate, key string) Option

WithTSLConfig sets the `key` and `certificate` of TSL

func WithTimerPrecision added in v1.0.0

func WithTimerPrecision(precision time.Duration) Option

WithTimerPrecision sets the ticker precision, and time precision can not less than a Millisecond, and can not change after application running. The default precision is time.Second

func WithVersion added in v1.0.0

func WithVersion(version string) Option

WithVersion sets the current node version in cluster

func WithWebSocketCompression added in v1.1.32

func WithWebSocketCompression() Option

type SessionFilter

type SessionFilter func(*session.Session) bool

SessionFilter represents a filter which was used to filter session when Multicast, the session will receive the message while filter returns true.

Directories

Path Synopsis
benchmark
io
env represents the environment of the current process, includes work path and config path etc.
env represents the environment of the current process, includes work path and config path etc.

Jump to

Keyboard shortcuts

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