simple

package
v1.6.7 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 18 Imported by: 3

README

简单化版的网络数据包解析实现

  • 起因是网友@刘在Q群中反馈,需要一个更简单的网络数据包结构。
  • 本结构只是一个自定义网络数据包的演示。在实际开发中各位可根据自身需求进行定制。
  • 代码未做详细测试,并且缺少对应的客户端实现。在使用中有任何问题欢迎反馈。
包结构
  • 本结构参照zinx的网络包结构,通过消息ID + 数据长度 + 数据构建一个网络数据包
  • MID uint32(4 bytes) + DataLen uint32(4 bytes) + Data(n bytes)
使用方法
  • 在网关节点构建一个simple的网络数据包解析器
  • 通过simple.AddNodeRoute(mid,&NodeRoute{...})构造数据包路由策略
  • 示例代码
示例代码
// 构建简单的网络数据包解析器
func buildSimpleParser(app *cherry.AppBuilder) cfacade.INetParser {
    agentActor := simple.NewActor("user")
    agentActor.AddConnector(cconnector.NewTCP(":10011"))
    agentActor.AddConnector(cconnector.NewWS(app.Address()))
	
        agentActor.SetOnNewAgent(func(newAgent *simple.Agent) {
        childActor := &ActorAgent{}
        //newAgent.AddOnClose(childActor.onSessionClose)
        agentActor.Child().Create(newAgent.SID(), childActor)
    })

    // 设置大头&小头
    agentActor.SetEndian(binary.LittleEndian)
    // 设置心跳时间
    agentActor.SetHeartbeatTime(60 * time.Second)
    // 设置积压消息数量
    agentActor.SetWriteBacklog(64)

    // 设置数据路由函数
    //agentActor.SetOnDataRoute(onSimpleDataRoute)

    // 设置消息节点路由(建议配合data-config配置表使用)
    // mid = 1 的消息路由到  gate节点.user的Actor.login函数上
    agentActor.AddNodeRoute(1, &simple.NodeRoute{
        NodeType: "gate",
        ActorID:  "user",
        FuncName: "login",
    })
	
    return agentActor
}

Documentation

Index

Constants

View Source
const (
	AgentInit   int32 = 0 // initial state
	AgentClosed int32 = 4 // closed, no further processing
)

Agent lifecycle states.

View Source
const (
	ResponseFuncName = "response"
)

Remote function name constants.

Variables

View Source
var (
	NoneMessage = Message{} // zero-value sentinel

)

Package-level message constants.

Functions

func AddNodeRoute

func AddNodeRoute(mid uint32, nodeRoute *NodeRoute)

AddNodeRoute maps a mid (message id) to a NodeRoute for routing incoming messages.

func BindSID

func BindSID(agent *Agent)

BindSID registers an agent in the sid lookup map.

func ClusterLocalDataRoute

func ClusterLocalDataRoute(agent *Agent, session *cproto.Session, msg *Message, nodeRoute *NodeRoute, nodeID, targetPath string) error

ClusterLocalDataRoute publishes a message to a local actor on a remote node via the cluster.

func Count

func Count() int

Count returns the total number of connected agents.

func DefaultDataRoute

func DefaultDataRoute(agent *Agent, msg *Message, route *NodeRoute)

DefaultDataRoute is the default message routing handler. It dispatches locally when the target node type matches the agent's node, or forwards to a random member of the target node type via the cluster.

func ForeachAgent

func ForeachAgent(fn func(a *Agent))

ForeachAgent iterates over all connected agents.

func GetSID added in v1.6.7

func GetSID(uid int64) (cfacade.SID, bool)

GetSID returns the session id bound to the given user id.

func LocalDataRoute

func LocalDataRoute(agent *Agent, session *cproto.Session, msg *Message, nodeRoute *NodeRoute, targetPath string)

LocalDataRoute posts a message to a local actor on this node.

func Response

func Response(iActor cfacade.IActor, session *cproto.Session, mid uint32, v interface{})

Response looks up the agent by the session and sends a response payload back to the client.

func SetEndian

func SetEndian(e binary.ByteOrder)

SetEndian sets the byte order used for encoding/decoding message headers.

func SetHeartbeatTime

func SetHeartbeatTime(t time.Duration)

SetHeartbeatTime sets the heartbeat interval for agent connections. Values less than 1 second are ignored.

func SetWriteBacklog

func SetWriteBacklog(backlog int)

SetWriteBacklog sets the size of the write and pending channel buffers. Values less than or equal to 0 are ignored.

func Unbind

func Unbind(sid cfacade.SID)

Unbind removes the sid→agent mapping and cleans up the uid→sid entry if it still points to this sid.

Types

type Actor added in v1.6.7

type Actor struct {
	cactor.Base
	// contains filtered or unexported fields
}

func NewActor

func NewActor(agentActorID string) *Actor

NewActor creates a new simple parser Actor with the given agent actor id.

func (*Actor) AddConnector added in v1.6.7

func (p *Actor) AddConnector(connector cfacade.IConnector)

AddConnector registers a connector that will be started when the parser loads.

func (*Actor) AddNodeRoute added in v1.6.7

func (p *Actor) AddNodeRoute(mid uint32, nodeRoute *NodeRoute)

AddNodeRoute maps a mid (message id) to a NodeRoute for routing incoming messages.

func (*Actor) Connectors added in v1.6.7

func (p *Actor) Connectors() []cfacade.IConnector

Connectors returns the list of registered connectors.

func (*Actor) Load added in v1.6.7

func (p *Actor) Load(app cfacade.IApplication)

Load starts the parser: creates the agent actor and starts all registered connectors.

func (*Actor) OnInit added in v1.6.7

func (p *Actor) OnInit()

OnInit Actor初始化前触发该函数

func (*Actor) SetEndian added in v1.6.7

func (p *Actor) SetEndian(e binary.ByteOrder)

SetEndian sets the byte order used for encoding/decoding message headers.

func (*Actor) SetHeartbeatTime added in v1.6.7

func (p *Actor) SetHeartbeatTime(t time.Duration)

SetHeartbeatTime sets the heartbeat interval for agent connections.

func (*Actor) SetOnDataRoute added in v1.6.7

func (*Actor) SetOnDataRoute(fn DataRouteFunc)

SetOnDataRoute sets the callback that handles routing of incoming data messages.

func (*Actor) SetOnNewAgent added in v1.6.7

func (p *Actor) SetOnNewAgent(fn OnNewAgentFunc)

SetOnNewAgent sets the callback that is invoked when a new agent connection is established.

func (*Actor) SetWriteBacklog added in v1.6.7

func (p *Actor) SetWriteBacklog(backlog int)

SetWriteBacklog sets the size of the write and pending channel buffers.

type ActorBase

type ActorBase struct {
	cactor.Base
}

ActorBase provides convenience methods for actors to respond to clients.

func (*ActorBase) Response

func (p *ActorBase) Response(session *cproto.Session, mid uint32, v interface{})

Response sends a response payload back to the client for the given session and message id.

type Agent

type Agent struct {
	cfacade.IApplication // app
	// contains filtered or unexported fields
}

Agent represents a single client connection. All conn.Write and teardown operations happen exclusively in writeChan's goroutine.

func Bind added in v1.5.3

func Bind(sid cfacade.SID, uid cfacade.UID) (*Agent, error)

Bind associates a uid with an existing sid. Returns any previously bound agent for the same uid (duplicate login).

func GetAgent

func GetAgent(sid string, uid cfacade.UID) (*Agent, bool)

GetAgent resolves an agent by sid first, falling back to uid.

func GetAgentWithSID added in v1.5.3

func GetAgentWithSID(sid cfacade.SID) (*Agent, bool)

GetAgentWithSID looks up an agent by session id.

func GetAgentWithUID

func GetAgentWithUID(uid cfacade.UID) (*Agent, bool)

GetAgentWithUID looks up an agent by user id.

func NewAgent

func NewAgent(app cfacade.IApplication, conn net.Conn, sid cfacade.SID, agentPath string) *Agent

NewAgent creates an agent for a new connection. It is the only way to build a usable one: every field but the embedded application is unexported, so an Agent literal written elsewhere has no connection, no channels and no session data. Binding it into the lookup maps afterwards is the caller's job — see BindSID.

sid and agentPath are connection identity: they are captured here and never change, so any goroutine may read them. The session key/values start empty and are reached through Data.

func (*Agent) AddOnClose

func (a *Agent) AddOnClose(fn OnCloseFunc)

func (*Agent) AgentPath added in v1.6.7

func (a *Agent) AgentPath() string

AgentPath returns the parser actor path this connection belongs to.

func (*Agent) Bind

func (a *Agent) Bind(uid cfacade.UID) (*Agent, error)

func (*Agent) Close

func (a *Agent) Close()

func (*Agent) Data added in v1.6.7

func (a *Agent) Data() *cproto.SessionData

Data returns this connection's session key/values. Its methods are safe to call from any goroutine.

func (*Agent) GetData added in v1.6.7

func (a *Agent) GetData(key string) string

GetData reads one session value off this connection — shorthand for Data().Get, for the common case of reading a single key.

func (*Agent) IP added in v1.6.7

func (a *Agent) IP() string

IP returns the client ip address.

func (*Agent) IsClosed added in v1.5.3

func (a *Agent) IsClosed() bool

func (*Agent) Kick added in v1.3.16

func (a *Agent) Kick(mid uint32, reason interface{}, closed bool)

func (*Agent) NewSession added in v1.6.7

func (a *Agent) NewSession(mid uint32) *cproto.Session

NewSession builds a session for one message of this connection: a new object carrying the connection's identity, a copy of its session data, and mid.

A new object on every call is the point: writing the message id onto one session shared by the connection's goroutines is a data race. Pass 0 where a session is needed but no message is being routed.

func (*Agent) RemoteAddr

func (a *Agent) RemoteAddr() string

func (*Agent) Response

func (a *Agent) Response(mid uint32, v interface{})

func (*Agent) Run

func (a *Agent) Run()

func (*Agent) SID

func (a *Agent) SID() cfacade.SID

SID returns the session id.

func (*Agent) SendKick added in v1.5.3

func (a *Agent) SendKick(pkg []byte)

func (*Agent) SendRaw

func (a *Agent) SendRaw(bytes []byte)

func (*Agent) SetData added in v1.6.7

func (a *Agent) SetData(key, value string)

SetData writes one session value on this connection — shorthand for Data().Set.

func (*Agent) SetLastAt

func (a *Agent) SetLastAt()

func (*Agent) SetState

func (a *Agent) SetState(state int32) bool

func (*Agent) SetUID added in v1.6.7

func (a *Agent) SetUID(uid cfacade.UID)

SetUID binds a user id to this connection.

func (*Agent) State

func (a *Agent) State() int32

func (*Agent) UID

func (a *Agent) UID() cfacade.UID

UID returns the bound user id.

func (*Agent) Unbind

func (a *Agent) Unbind()

type DataRouteFunc

type DataRouteFunc func(agent *Agent, msg *Message, route *NodeRoute)

DataRouteFunc is called to route a decoded message to the target actor.

type Message

type Message struct {
	MID  uint32 // message id for request/response matching
	Len  uint32 // length of the data payload
	Data []byte // payload bytes
}

Message represents a decoded simple-protocol message. The wire format is: MID(4 bytes) + DataLen(4 bytes) + Data(DataLen bytes).

func ReadMessage

func ReadMessage(conn net.Conn) (Message, bool, error)

ReadMessage reads and parses a single message from the connection. It returns the message, a break flag (true if the connection should be considered closed), and any error encountered.

type NodeRoute

type NodeRoute struct {
	NodeType string // target node type
	ActorID  string // target actor id
	FuncName string // target function name
}

NodeRoute describes the target actor and function for a given message id.

func GetNodeRoute

func GetNodeRoute(mid uint32) (*NodeRoute, bool)

GetNodeRoute returns the NodeRoute for the given message id.

type OnCloseFunc

type OnCloseFunc func(*Agent)

type OnNewAgentFunc

type OnNewAgentFunc func(newAgent *Agent)

Jump to

Keyboard shortcuts

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