simple

package
v1.5.3 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2026 License: MIT Imports: 18 Imported by: 2

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 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 NewActor

func NewActor(agentActorID string) *actor

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

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 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
	// 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 (public).

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, session *cproto.Session) *Agent

NewAgent creates an agent for a new connection.

func (*Agent) AddOnClose

func (a *Agent) AddOnClose(fn OnCloseFunc)

func (*Agent) Bind

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

func (*Agent) Close

func (a *Agent) Close()

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) 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

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) Session

func (a *Agent) Session() *cproto.Session

func (*Agent) SetLastAt

func (a *Agent) SetLastAt()

func (*Agent) SetState

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

func (*Agent) State

func (a *Agent) State() int32

func (*Agent) UID

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

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