iface

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 19, 2023 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

@Title iclient.go @Description Provides all interface declarations for the Client abstraction layer.

@Title iconnection.go @Description Declaration of all connection-related methods

@Title iconnmanager.go @Description Connection management related operations, including adding, removing, getting a connection object by a connection ID, methods to get the current number of connections and clear all connections.

@Title idatapack.go @Description Message packing and unpacking methods

@Title imessage.go @Description Provides basic methods for messages

@Title imsghandler.go @Description Provides interfaces for worker startup and handling message business calls

@Title irequest.go @Description Provides all interface declarations for connection requests

@Title irouter.go @Description Provides all interface declarations for message routing

@Title iserver.go @Description Provides all interface declarations for the Server abstraction layer

Index

Constants

View Source
const (
	// Zinx standard packing and unpacking method (Zinx 标准封包和拆包方式)
	ZinxDataPack    string = "zinx_pack_tlv_big_endian"
	ZinxDataPackOld string = "zinx_pack_ltv_little_endian"
)
View Source
const (
	HeartBeatDefaultMsgID uint32 = 99999
)
View Source
const (
	// Zinx default standard message protocol format(Zinx 默认标准报文协议格式)
	ZinxMessage string = "zinx_message"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseRequest

type BaseRequest struct{}

func (*BaseRequest) Abort

func (br *BaseRequest) Abort()

func (*BaseRequest) BindRouter

func (br *BaseRequest) BindRouter(router IRouter)

func (*BaseRequest) BindRouterSlices

func (br *BaseRequest) BindRouterSlices([]RouterHandler)

func (*BaseRequest) Call

func (br *BaseRequest) Call()

func (*BaseRequest) GetConnection

func (br *BaseRequest) GetConnection() IConnection

func (*BaseRequest) GetData

func (br *BaseRequest) GetData() []byte

func (*BaseRequest) GetMessage

func (br *BaseRequest) GetMessage() IMessage

func (*BaseRequest) GetMsgID

func (br *BaseRequest) GetMsgID() uint32

func (*BaseRequest) GetResponse

func (br *BaseRequest) GetResponse() IcResp

func (*BaseRequest) Goto

func (br *BaseRequest) Goto(HandleStep)

func (*BaseRequest) RouterSlicesNext

func (br *BaseRequest) RouterSlicesNext()

func (*BaseRequest) SetResponse

func (br *BaseRequest) SetResponse(resp IcResp)

type HandleStep

type HandleStep int

type HeartBeatFunc

type HeartBeatFunc func(IConnection) error

HeartBeatFunc User-defined heartbeat function (用户自定义心跳函数)

type HeartBeatMsgFunc

type HeartBeatMsgFunc func(IConnection) []byte

User-defined method for handling heartbeat detection messages (用户自定义的心跳检测消息处理方法)

type HeartBeatOption

type HeartBeatOption struct {
	MakeMsg          HeartBeatMsgFunc // User-defined method for handling heartbeat detection messages(用户自定义的心跳检测消息处理方法)
	OnRemoteNotAlive OnRemoteNotAlive // User-defined method for handling remote connections that are not alive(用户自定义的远程连接不存活时的处理方法)
	HeadBeatMsgID    uint32           // User-defined ID for heartbeat detection messages(用户自定义的心跳检测消息ID)
	Router           IRouter          // User-defined business processing route for heartbeat detection messages(用户自定义的心跳检测消息业务处理路由)
	RouterSlices     []RouterHandler  //新版本的路由处理函数的集合
}

type IChain

type IChain interface {
	Request() IcReq        // Get the request data in the current chain (current interceptor)-获取当前责任链中的请求数据(当前拦截器)
	GetIMessage() IMessage // Get IMessage from Chain (从Chain中获取IMessage)
	Proceed(IcReq) IcResp  // Enter and execute the next interceptor, and pass the request data to the next interceptor (进入并执行下一个拦截器,且将请求数据传递给下一个拦截器)
	ProceedWithIMessage(IMessage, IcReq) IcResp
}

Responsibility chain (责任链)

type IClient

type IClient interface {
	Restart()
	Start()
	Stop()
	AddRouter(msgID uint32, router IRouter)
	Conn() IConnection

	// SetOnConnStart Set the Hook function to be called when a connection is created for this Client
	// (设置该Client的连接创建时Hook函数)
	SetOnConnStart(func(IConnection))

	// SetOnConnStop Set the Hook function to be called when a connection is closed for this Client
	// (设置该Client的连接断开时的Hook函数)
	SetOnConnStop(func(IConnection))

	// GetOnConnStart Get the Hook function that is called when a connection is created for this Client
	// (获取该Client的连接创建时Hook函数)
	GetOnConnStart() func(IConnection)

	// GetOnConnStop Get the Hook function that is called when a connection is closed for this Client
	// (设置该Client的连接断开时的Hook函数)
	GetOnConnStop() func(IConnection)

	// GetPacket Get the data protocol packet binding method for this Client
	// (获取Client绑定的数据协议封包方式)
	GetPacket() IDataPack

	// SetPacket Set the data protocol packet binding method for this Client
	// (设置Client绑定的数据协议封包方式)
	SetPacket(IDataPack)

	// GetMsgHandler Get the message handling module bound to this Client
	// (获取Client绑定的消息处理模块)
	GetMsgHandler() IMsgHandle

	// StartHeartBeat Start heartbeat detection(启动心跳检测)
	StartHeartBeat(time.Duration)

	// StartHeartBeatWithOption Start heartbeat detection with custom callbacks 启动心跳检测(自定义回调)
	StartHeartBeatWithOption(time.Duration, *HeartBeatOption)

	// GetLengthField Get the length field of this Client
	GetLengthField() *LengthField

	// SetDecoder Set the decoder for this Client 设置解码器
	SetDecoder(IDecoder)

	// AddInterceptor Add an interceptor for this Client 添加拦截器
	AddInterceptor(IInterceptor)

	// Get the error channel for this Client 获取客户端错误管道
	GetErrChan() chan error

	// Set the name of this Clien
	// 设置客户端Client名称
	SetName(string)

	// Get the name of this Client
	// 获取客户端Client名称
	GetName() string
}

type IConnManager

type IConnManager interface {
	Add(IConnection)                                                       // Add connection
	Remove(IConnection)                                                    // Remove connection
	Get(uint64) (IConnection, error)                                       // Get a connection by ConnID
	Len() int                                                              // Get current number of connections
	ClearConn()                                                            // Remove and stop all connections
	GetAllConnID() []uint64                                                // Get all connection IDs
	Range(func(uint64, IConnection, interface{}) error, interface{}) error // Traverse all connections
}

Connection Management Abstract Layer

type IConnection

type IConnection interface {
	// Start the connection, make the current connection start working
	// (启动连接,让当前连接开始工作)
	Start()
	// Stop the connection and end the current connection state
	// (停止连接,结束当前连接状态)
	Stop()

	// Returns ctx, used by user-defined go routines to obtain connection exit status
	// (返回ctx,用于用户自定义的go程获取连接退出状态)
	Context() context.Context

	GetName() string            // Get the current connection name (获取当前连接名称)
	GetConnection() net.Conn    // Get the original socket from the current connection(从当前连接获取原始的socket)
	GetWsConn() *websocket.Conn // Get the original websocket connection from the current connection(从当前连接中获取原始的websocket连接)
	// Deprecated: use GetConnection instead
	GetTCPConnection() net.Conn // Get the original socket TCPConn from the current connection (从当前连接获取原始的socket TCPConn)
	GetConnID() uint64          // Get the current connection ID (获取当前连接ID)
	GetMsgHandler() IMsgHandle  // Get the message handler (获取消息处理器)
	RemoteAddr() net.Addr       // Get the remote address information of the connection (获取链接远程地址信息)
	LocalAddr() net.Addr        // Get the local address information of the connection (获取链接本地地址信息)
	LocalAddrString() string    // Get the local address information of the connection as a string
	RemoteAddrString() string   // Get the remote address information of the connection as a string

	Send(data []byte) error        // Send data directly to the remote TCP client (without buffering)
	SendToQueue(data []byte) error // Send data to the message queue to be sent to the remote TCP client later

	// Send Message data directly to the remote TCP client (without buffering)
	// 直接将Message数据发送数据给远程的TCP客户端(无缓冲)
	SendMsg(msgID uint32, data []byte) error

	// Send Message data to the message queue to be sent to the remote TCP client later (with buffering)
	// 直接将Message数据发送给远程的TCP客户端(有缓冲)
	SendBuffMsg(msgID uint32, data []byte) error

	SetProperty(key string, value interface{})   // Set connection property
	GetProperty(key string) (interface{}, error) // Get connection property
	RemoveProperty(key string)                   // Remove connection property
	IsAlive() bool                               // Check if the current connection is alive(判断当前连接是否存活)
	SetHeartBeat(checker IHeartbeatChecker)      // Set the heartbeat detector (设置心跳检测器)
}

// Define connection interface

type IDataPack

type IDataPack interface {
	GetHeadLen() uint32                // Get the length of the message header(获取包头长度方法)
	Pack(msg IMessage) ([]byte, error) // Package message (封包方法)
	Unpack([]byte) (IMessage, error)   // Unpackage message(拆包方法)
}

Package and unpack data. Operating on the data stream of TCP connections, add header information to transfer data, and solve TCP sticky packets. (封包数据和拆包数据 直接面向TCP连接中的数据流,为传输数据添加头部信息,用于处理TCP粘包问题。)

type IDecoder

type IDecoder interface {
	IInterceptor
	GetLengthField() *LengthField
}

type IFrameDecoder

type IFrameDecoder interface {
	Decode(buff []byte) [][]byte
}

type IFuncRequest

type IFuncRequest interface {
	CallFunc()
}

IFuncRequest function message interface (函数消息接口)

type IGroupRouterSlices

type IGroupRouterSlices interface {
	// Add global components (添加全局组件)
	Use(Handlers ...RouterHandler)

	// Add group routing components (添加业务处理器集合)
	AddHandler(MsgId uint32, Handlers ...RouterHandler)
}

type IHeartbeatChecker

type IHeartbeatChecker interface {
	SetOnRemoteNotAlive(OnRemoteNotAlive)
	SetHeartbeatMsgFunc(HeartBeatMsgFunc)
	SetHeartbeatFunc(HeartBeatFunc)
	BindRouter(uint32, IRouter)
	BindRouterSlices(uint32, ...RouterHandler)
	Start()
	Stop()
	SendHeartBeatMsg() error
	BindConn(IConnection)
	Clone() IHeartbeatChecker
	MsgID() uint32
	Router() IRouter
	RouterSlices() []RouterHandler
}

type IInterceptor

type IInterceptor interface {
	Intercept(IChain) IcResp
}

Interceptor (拦截器)

type ILogger

type ILogger interface {
	//without context
	InfoF(format string, v ...interface{})
	ErrorF(format string, v ...interface{})
	DebugF(format string, v ...interface{})

	//with context
	InfoFX(ctx context.Context, format string, v ...interface{})
	ErrorFX(ctx context.Context, format string, v ...interface{})
	DebugFX(ctx context.Context, format string, v ...interface{})
}

type IMessage

type IMessage interface {
	GetDataLen() uint32 // Gets the length of the message data segment(获取消息数据段长度)
	GetMsgID() uint32   // Gets the ID of the message(获取消息ID)
	GetData() []byte    // Gets the content of the message(获取消息内容)
	GetRawData() []byte // Gets the raw data of the message(获取原始数据)

	SetMsgID(uint32)   // Sets the ID of the message(设计消息ID)
	SetData([]byte)    // Sets the content of the message(设计消息内容)
	SetDataLen(uint32) // Sets the length of the message data segment(设置消息数据段长度)
}

Package ziface defines an abstract interface for encapsulating a request message into a message

type IMsgHandle

type IMsgHandle interface {
	// Add specific handling logic for messages, msgID supports int and string types
	// (为消息添加具体的处理逻辑, msgID,支持整型,字符串)
	AddRouter(msgID uint32, router IRouter)
	AddRouterSlices(msgId uint32, handler ...RouterHandler) IRouterSlices
	Group(start, end uint32, Handlers ...RouterHandler) IGroupRouterSlices
	Use(Handlers ...RouterHandler) IRouterSlices

	StartWorkerPool()                    //  Start the worker pool
	SendMsgToTaskQueue(request IRequest) // Pass the message to the TaskQueue for processing by the worker(将消息交给TaskQueue,由worker进行处理)

	Execute(request IRequest) // Execute interceptor methods on the responsibility chain(执行责任链上的拦截器方法)

	// Register the entry point of the responsibility chain. After each interceptor is processed,
	// the data is passed to the next interceptor, so that the message can be handled and passed layer by layer,
	// the order depends on the registration order
	// (注册责任链任务入口,每个拦截器处理完后,数据都会传递至下一个拦截器,使得消息可以层层处理层层传递,顺序取决于注册顺序)
	AddInterceptor(interceptor IInterceptor)
}

Abstract layer of message management(消息管理抽象层)

type IRequest

type IRequest interface {
	GetConnection() IConnection // Get the connection information of the request(获取请求连接信息)

	GetData() []byte  // Get the data of the request message(获取请求消息的数据)
	GetMsgID() uint32 // Get the message ID of the request(获取请求的消息ID)

	GetMessage() IMessage // Get the raw data of the request message (获取请求消息的原始数据 add by uuxia 2023-03-10)

	GetResponse() IcResp // Get the serialized data after parsing(获取解析完后序列化数据)
	SetResponse(IcResp)  // Set the serialized data after parsing(设置解析完后序列化数据)

	BindRouter(router IRouter) // Bind which router handles this request(绑定这次请求由哪个路由处理)
	// Move on to the next handler to start execution, but the function that calls this method will execute in reverse order of their order
	// (转进到下一个处理器开始执行 但是调用此方法的函数会根据先后顺序逆序执行)
	Call()

	//erminate the execution of the processing function, but the function that calls this method will be executed until completion
	// 终止处理函数的运行 但调用此方法的函数会执行完毕
	Abort()

	//Specify which Handler function to execute next in the Handle
	// (指定接下来的Handle去执行哪个Handler函数)
	// Be careful, it will cause loop calling
	// (慎用,会导致循环调用)
	Goto(HandleStep)

	// New router operation
	// (新路由操作)
	BindRouterSlices([]RouterHandler)

	// Execute the next function
	// (执行下一个函数)
	RouterSlicesNext()
}

IRequest interface:

It actually packages the connection information and request data of the client request into Request
(实际上是把客户端请求的链接信息 和 请求的数据 包装到了 Request里)

type IRouter

type IRouter interface {
	PreHandle(request IRequest)  //Hook method before processing conn business(在处理conn业务之前的钩子方法)
	Handle(request IRequest)     //Method for processing conn business(处理conn业务的方法)
	PostHandle(request IRequest) //Hook method after processing conn business(处理conn业务之后的钩子方法)
}

IRouter is the interface for message routing. The route is the processing business method set by the framework user for this connection. The IRequest in the route includes the connection information and the request data information for this connection. (路由接口, 这里面路由是 使用框架者给该链接自定的 处理业务方法 路由里的IRequest 则包含用该链接的链接信息和该链接的请求数据信息)

type IRouterSlices

type IRouterSlices interface {
	// Add global components (添加全局组件)
	Use(Handlers ...RouterHandler)

	// Add a route (添加业务处理器集合)
	AddHandler(msgId uint32, handlers ...RouterHandler)

	// Router group management (路由分组管理,并且会返回一个组管理器)
	Group(start, end uint32, Handlers ...RouterHandler) IGroupRouterSlices

	// Get the method set collection for processing (获得当前的所有注册在MsgId的处理器集合)
	GetHandlers(MsgId uint32) ([]RouterHandler, bool)
}

type IServer

type IServer interface {
	Start(ctx context.Context) error // Start the server method(启动服务器方法)
	Stop(ctx context.Context) error  // Stop the server method (停止服务器方法)
	Serve()                          // Start the business service method(开启业务服务方法) (废弃)

	// Routing feature: register a routing business method for the current service for client link processing use
	//(路由功能:给当前服务注册一个路由业务方法,供客户端链接处理使用)
	AddRouter(msgID uint32, router IRouter)

	// New version of routing (新版路由方式)
	AddRouterSlices(msgID uint32, router ...RouterHandler) IRouterSlices

	// Route group management (路由组管理)
	Group(start, end uint32, Handlers ...RouterHandler) IGroupRouterSlices

	// Common component management (公共组件管理)
	Use(Handlers ...RouterHandler) IRouterSlices

	// Get connection management (得到链接管理)
	GetConnMgr() IConnManager

	// Set Hook function when the connection is created for the Server (设置该Server的连接创建时Hook函数)
	SetOnConnStart(func(IConnection))

	// Set Hook function when the connection is disconnected for the Server
	// (设置该Server的连接断开时的Hook函数)
	SetOnConnStop(func(IConnection))

	// Get Hook function when the connection is created for the Server
	// (得到该Server的连接创建时Hook函数)
	GetOnConnStart() func(IConnection)

	// Get Hook function when the connection is disconnected for the Server
	// (得到该Server的连接断开时的Hook函数)
	GetOnConnStop() func(IConnection)

	// Get the data protocol packet binding method for the Server
	// (获取Server绑定的数据协议封包方式)
	GetPacket() IDataPack

	// Get the message processing module binding method for the Server
	// (获取Server绑定的消息处理模块)
	GetMsgHandler() IMsgHandle

	// Set the data protocol packet binding method for the Server
	// (设置Server绑定的数据协议封包方式)
	SetPacket(IDataPack)

	// Start the heartbeat check
	// (启动心跳检测)
	StartHeartBeat(time.Duration)

	// Start the heartbeat check (custom callback)
	// 启动心跳检测(自定义回调)
	StartHeartBeatWithOption(time.Duration, *HeartBeatOption)

	// Get the heartbeat checker
	// (获取心跳检测器)
	GetHeartBeat() IHeartbeatChecker

	GetLengthField() *LengthField
	SetDecoder(IDecoder)
	AddInterceptor(IInterceptor)

	// Add WebSocket authentication method
	// (添加websocket认证方法)
	SetWebsocketAuth(func(r *http.Request) error)

	// Get the server name (获取服务器名称)
	ServerName() string
}

Defines the server interface

type IcReq

type IcReq interface{}

Input data for interceptor (拦截器输入数据)

type IcResp

type IcResp interface{}

Output data for interceptor (拦截器输出数据)

type Inotify

type Inotify interface {
	// Whether there is a connection with this id
	// (是否有这个id)
	HasIdConn(id uint64) bool

	// Get the number of connections stored
	// (存储的map长度)
	ConnNums() int

	// Add a connection
	// (添加链接)
	SetNotifyID(Id uint64, conn IConnection)

	// Get a connection by id
	// (得到某个链接)
	GetNotifyByID(Id uint64) (IConnection, error)

	// Delete a connection by id
	// (删除某个链接)
	DelNotifyByID(Id uint64)

	// Notify a connection with the given id
	// (通知某个id的方法)
	NotifyToConnByID(Id uint64, MsgId uint32, data []byte) error

	// Notify all connections
	// (通知所有人)
	NotifyAll(MsgId uint32, data []byte) error

	// Notify a connection with the given id using a buffer queue
	// (通过缓冲队列通知某个id的方法)
	NotifyBuffToConnByID(Id uint64, MsgId uint32, data []byte) error

	// Notify all connections using a buffer queue
	// (缓冲队列通知所有人)
	NotifyBuffAll(MsgId uint32, data []byte) error
}

type LengthField

type LengthField struct {
	/*
		Note:
		   Big-endian: the most significant byte (the "big end") of a word is placed at the byte with the lowest address;
		   the rest of the bytes are placed in order of decreasing significance towards the byte with the highest address.
		   Little-endian: the least significant byte (the "little end") of a word is placed at the byte with the lowest address;
		   the rest of the bytes are placed in order of increasing significance towards the byte with the highest address.
		(大端模式:是指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中,地址由小向大增加,而数据从高位往低位放;
		小端模式:是指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中,高地址部分权值高,低地址部分权值低,和我们的日常逻辑方法一致。)
	*/
	Order               binary.ByteOrder //The byte order: BigEndian or LittleEndian(大小端)
	MaxFrameLength      uint64           //The maximum length of a frame(最大帧长度)
	LengthFieldOffset   int              //The offset of the length field(长度字段偏移量)
	LengthFieldLength   int              //The length of the length field in bytes(长度域字段的字节数)
	LengthAdjustment    int              //The length adjustment(长度调整)
	InitialBytesToStrip int              //The number of bytes to strip from the decoded frame(需要跳过的字节数)
}

ILengthField Basic attributes possessed by ILengthField (具备的基础属性)

type OnRemoteNotAlive

type OnRemoteNotAlive func(IConnection)

OnRemoteNotAlive User-defined method for handling remote connections that are not alive 用户自定义的远程连接不存活时的处理方法

type RouterHandler

type RouterHandler func(request IRequest)

RouterHandler is a method slice collection style router. Unlike the old version, the new version only saves the router method collection, and the specific execution is handed over to the IRequest of each request. (方法切片集合式路路由 不同于旧版 新版本仅保存路由方法集合,具体执行交给每个请求的 IRequest)

Jump to

Keyboard shortcuts

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