server

package
v0.0.14 Latest Latest
Warning

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

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

Documentation

Overview

Package server 提供了包含多种网络类型的服务器实现

Index

Examples

Constants

View Source
const (
	DefaultMessageBufferSize     = 1024
	DefaultMessageChannelSize    = 1024 * 64
	DefaultAsyncPoolSize         = 256
	DefaultWebsocketReadDeadline = 30 * time.Second
)
View Source
const (
	// WebsocketMessageTypeText 表示文本数据消息。文本消息负载被解释为 UTF-8 编码的文本数据
	WebsocketMessageTypeText = 1
	// WebsocketMessageTypeBinary 表示二进制数据消息
	WebsocketMessageTypeBinary = 2
	// WebsocketMessageTypeClose 表示关闭控制消息。可选消息负载包含数字代码和文本。使用 FormatCloseMessage 函数来格式化关闭消息负载
	WebsocketMessageTypeClose = 8
	// WebsocketMessageTypePing 表示 ping 控制消息。可选的消息负载是 UTF-8 编码的文本
	WebsocketMessageTypePing = 9
	// WebsocketMessageTypePong 表示一个 pong 控制消息。可选的消息负载是 UTF-8 编码的文本
	WebsocketMessageTypePong = 10
)

Variables

View Source
var (
	ErrConstructed                 = errors.New("the Server must be constructed using the server.New function")
	ErrCanNotSupportNetwork        = errors.New("can not support network")
	ErrNetworkOnlySupportHttp      = errors.New("the current network mode is not compatible with HttpRouter, only NetworkHttp is supported")
	ErrNetworkOnlySupportGRPC      = errors.New("the current network mode is not compatible with RegGrpcServer, only NetworkGRPC is supported")
	ErrNetworkIncompatibleHttp     = errors.New("the current network mode is not compatible with NetworkHttp")
	ErrWebsocketIllegalMessageType = errors.New("illegal message type")
	ErrNoSupportCross              = errors.New("the server does not support GetID or PushCrossMessage, please use the WithCross option to create the server")
	ErrNoSupportTicker             = errors.New("the server does not support Ticker, please use the WithTicker option to create the server")
)

Functions

func PushAsyncMessage added in v0.0.10

func PushAsyncMessage(srv *Server, caller func() error, callback func(err error), mark ...any)

PushAsyncMessage 向特定服务器中推送 MessageTypeAsync 消息

func PushCrossMessage added in v0.0.10

func PushCrossMessage(srv *Server, crossName string, serverId int64, packet []byte, mark ...any)

PushCrossMessage 向特定服务器中推送 MessageTypeCross 消息

func PushErrorMessage added in v0.0.10

func PushErrorMessage(srv *Server, err error, action MessageErrorAction, mark ...any)

PushErrorMessage 向特定服务器中推送 MessageTypeError 消息

func PushPacketMessage added in v0.0.10

func PushPacketMessage(srv *Server, conn *Conn, packet []byte, mark ...any)

PushPacketMessage 向特定服务器中推送 MessageTypePacket 消息

func PushTickerMessage added in v0.0.10

func PushTickerMessage(srv *Server, caller func(), mark ...any)

PushTickerMessage 向特定服务器中推送 MessageTypeTicker 消息

func SetMessagePacketVisualizer added in v0.0.14

func SetMessagePacketVisualizer(handle func(packet []byte) string)

SetMessagePacketVisualizer 设置消息可视化函数

  • 消息可视化将在慢消息等情况用于打印,使用自定消息可视化函数可以便于开发者进行调试
  • 默认的消息可视化函数将直接返回消息的字符串表示

Types

type Conn

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

Conn 服务器连接

func (*Conn) Close

func (slf *Conn) Close()

Close 关闭连接

func (*Conn) GetData

func (slf *Conn) GetData(key any) any

GetData 获取连接数据

func (*Conn) GetID

func (slf *Conn) GetID() string

GetID 获取连接ID

  • 为远程地址的字符串形式

func (*Conn) GetIP

func (slf *Conn) GetIP() string

GetIP 获取连接IP

func (*Conn) IsWebsocket

func (slf *Conn) IsWebsocket() bool

IsWebsocket 是否是websocket连接

func (*Conn) ReleaseData

func (slf *Conn) ReleaseData() *Conn

ReleaseData 释放数据

func (*Conn) RemoteAddr

func (slf *Conn) RemoteAddr() net.Addr

RemoteAddr 获取远程地址

func (*Conn) Reuse added in v0.0.8

func (slf *Conn) Reuse(conn *Conn)

Reuse 重用连接

  • 重用连接时,会将当前连接的数据复制到新连接中
  • 通常在于连接断开后,重新连接时使用

func (*Conn) SetData

func (slf *Conn) SetData(key, value any) *Conn

SetData 设置连接数据

func (*Conn) Write

func (slf *Conn) Write(packet Packet)

Write 向连接中写入数据

  • messageType: websocket模式中指定消息类型

func (*Conn) WriteWithCallback added in v0.0.8

func (slf *Conn) WriteWithCallback(packet Packet, callback func(err error), messageType ...int)

WriteWithCallback 与 Write 相同,但是会在写入完成后调用 callback

  • 当 callback 为 nil 时,与 Write 相同

type ConnReadonly added in v0.0.4

type ConnReadonly interface {
	// RemoteAddr 获取远程地址
	RemoteAddr() net.Addr
	// GetID 获取连接 ID
	GetID() string
	// GetIP 获取连接 IP
	GetIP() string
	// GetData 获取连接数据
	GetData(key any) any
	// IsWebsocket 是否是 websocket 连接
	IsWebsocket() bool
}

ConnReadonly 连接只读接口

type ConnectionClosedEventHandle

type ConnectionClosedEventHandle func(srv *Server, conn *Conn, err any)

type ConnectionOpenedEventHandle

type ConnectionOpenedEventHandle func(srv *Server, conn *Conn)

type ConnectionReceivePacketEventHandle

type ConnectionReceivePacketEventHandle func(srv *Server, conn *Conn, packet Packet)

type ConsoleCommandEventHandle

type ConsoleCommandEventHandle func(srv *Server)

type Cross

type Cross interface {
	// Init 初始化跨服
	//  - serverId: 本服id
	//  - packetHandle.serverId: 发送跨服消息的服务器id
	//  - packetHandle.packet: 数据包
	Init(server *Server, packetHandle func(serverId int64, packet []byte)) error
	// PushMessage 推送跨服消息
	//  - serverId: 目标服务器id
	PushMessage(serverId int64, packet []byte) error
	// Release 释放资源
	Release()
}

Cross 跨服接口

type Message

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

Message 服务器消息

func (*Message) String added in v0.0.11

func (slf *Message) String() string

String 返回消息的字符串表示

type MessageErrorAction

type MessageErrorAction byte

MessageErrorAction 错误消息类型操作

const (
	MessageErrorActionNone     MessageErrorAction = iota // 错误消息类型操作:将不会被进行任何特殊处理,仅进行日志输出
	MessageErrorActionShutdown                           // 错误消息类型操作:当接收到该类型的操作时,服务器将执行 Server.shutdown 函数
)

func (MessageErrorAction) String

func (slf MessageErrorAction) String() string

type MessageErrorEventHandle

type MessageErrorEventHandle func(srv *Server, message *Message, err error)

type MessageLowExecEventHandle

type MessageLowExecEventHandle func(srv *Server, message *Message, cost time.Duration)

type MessageType

type MessageType byte

MessageType 消息类型

const (
	// MessageTypePacket 数据包消息类型:该类型的数据将被发送到 ConnectionReceivePacketEvent 进行处理
	MessageTypePacket MessageType = iota

	// MessageTypeError 错误消息类型:根据不同的错误状态,将交由 Server 进行统一处理
	MessageTypeError

	// MessageTypeCross 跨服消息类型:将被推送到跨服的 Cross 实现中进行处理
	MessageTypeCross

	// MessageTypeTicker 定时器消息类型
	MessageTypeTicker

	// MessageTypeAsync 异步消息类型
	MessageTypeAsync
)

func (MessageType) String

func (slf MessageType) String() string

String 返回消息类型的字符串表示

type MultipleServer

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

func NewMultipleServer

func NewMultipleServer(serverHandle ...func() (addr string, srv *Server)) *MultipleServer

func (*MultipleServer) OnExitEvent added in v0.0.4

func (slf *MultipleServer) OnExitEvent()

func (*MultipleServer) RegExitEvent added in v0.0.4

func (slf *MultipleServer) RegExitEvent(handle func())

RegExitEvent 注册退出事件

func (*MultipleServer) Run

func (slf *MultipleServer) Run()

type Network

type Network string
const (
	NetworkTcp  Network = "tcp"
	NetworkTcp4 Network = "tcp4"
	NetworkTcp6 Network = "tcp6"
	NetworkUdp  Network = "udp"
	NetworkUdp4 Network = "udp4"
	NetworkUdp6 Network = "udp6"
	NetworkUnix Network = "unix"
	NetworkHttp Network = "http"
	// NetworkWebsocket 该模式下需要获取url参数值时,可以通过连接的GetData函数获取
	//  - 当有多个同名参数时,获取到的值为切片类型
	NetworkWebsocket Network = "websocket"
	NetworkKcp       Network = "kcp"
	NetworkGRPC      Network = "grpc"
)

type Option

type Option func(srv *Server)

func WithAsyncPoolSize added in v0.0.10

func WithAsyncPoolSize(size int) Option

WithAsyncPoolSize 通过指定异步消息池大小的方式创建服务器

  • 当通过 WithDisableAsyncMessage 禁用异步消息时,此选项无效
  • 默认值为 DefaultAsyncPoolSize

func WithCross

func WithCross(crossName string, serverId int64, cross Cross) Option

WithCross 通过跨服的方式创建服务器

  • 推送跨服消息时,将推送到对应 crossName 的跨服中间件中,crossName 可以满足不同功能采用不同的跨服/消息中间件
  • 通常情况下 crossName 仅需一个即可

func WithDeadlockDetect added in v0.0.10

func WithDeadlockDetect(t time.Duration) Option

WithDeadlockDetect 通过死锁、死循环、永久阻塞检测的方式创建服务器

  • 当检测到死锁、死循环、永久阻塞时,服务器将会生成 WARN 类型的日志,关键字为 "SuspectedDeadlock"
  • 默认不开启死锁检测

func WithDisableAsyncMessage added in v0.0.10

func WithDisableAsyncMessage() Option

WithDisableAsyncMessage 通过禁用异步消息的方式创建服务器

func WithGRPCServerOptions

func WithGRPCServerOptions(options ...grpc.ServerOption) Option

WithGRPCServerOptions 通过GRPC的可选项创建GRPC服务器

func WithMessageBufferSize

func WithMessageBufferSize(size int) Option

WithMessageBufferSize 通过特定的消息缓冲池大小运行服务器

  • 默认大小为 DefaultMessageBufferSize
  • 消息数量超出这个值的时候,消息处理将会造成更大的开销(频繁创建新的结构体),同时服务器将输出警告内容

func WithMessageChannelSize added in v0.0.12

func WithMessageChannelSize(size int) Option

WithMessageChannelSize 通过指定消息通道大小的方式创建服务器

  • 足够大的消息通道可以确保服务器在短时间内接收到大量的消息而不至于阻塞
  • 默认值为 DefaultMessageChannelSize

func WithPProf added in v0.0.12

func WithPProf(pattern ...string) Option

WithPProf 通过性能分析工具PProf创建服务器

func WithRunMode added in v0.0.13

func WithRunMode(mode RunMode) Option

WithRunMode 通过特定模式运行服务器

  • 默认为 RunModeDev

func WithTLS

func WithTLS(certFile, keyFile string) Option

WithTLS 通过安全传输层协议TLS创建服务器

  • 支持:Http、Websocket

func WithTicker

func WithTicker(size int, autonomy bool) Option

WithTicker 通过定时器创建服务器,为服务器添加定时器功能

  • autonomy:定时器是否独立运行(独立运行的情况下不会作为服务器消息运行,会导致并发问题)

func WithWebsocketCompression added in v0.0.12

func WithWebsocketCompression(level int) Option

WithWebsocketCompression 通过数据压缩的方式创建Websocket服务器

  • 默认不开启数据压缩

func WithWebsocketMessageType

func WithWebsocketMessageType(messageTypes ...int) Option

WithWebsocketMessageType 设置仅支持特定类型的Websocket消息

func WithWebsocketReadDeadline added in v0.0.8

func WithWebsocketReadDeadline(t time.Duration) Option

WithWebsocketReadDeadline 设置 Websocket 读取超时时间

  • 默认: DefaultWebsocketReadDeadline
  • 当 t <= 0 时,表示不设置超时时间

func WithWebsocketWriteCompression added in v0.0.12

func WithWebsocketWriteCompression() Option

WithWebsocketWriteCompression 通过数据写入压缩的方式创建Websocket服务器

  • 默认不开启数据压缩

type Packet added in v0.0.10

type Packet struct {
	WebsocketType int    // websocket 消息类型
	Data          []byte // 数据
}

Packet 数据包

func NewPacket added in v0.0.14

func NewPacket(data []byte) Packet

NewPacket 创建一个数据包

func NewPacketString added in v0.0.14

func NewPacketString(data string) Packet

NewPacketString 创建一个字符串数据包

func NewWSPacket added in v0.0.14

func NewWSPacket(websocketType int, data []byte) Packet

NewWSPacket 创建一个 websocket 数据包

func NewWSPacketString added in v0.0.14

func NewWSPacketString(websocketType int, data string) Packet

NewWSPacketString 创建一个 websocket 字符串数据包

func (Packet) String added in v0.0.10

func (slf Packet) String() string

String 转换为字符串

type ReceiveCrossPacketEventHandle

type ReceiveCrossPacketEventHandle func(srv *Server, senderServerId int64, packet []byte)

type RunMode added in v0.0.13

type RunMode = log.RunMode
const (
	RunModeDev  RunMode = log.RunModeDev
	RunModeProd RunMode = log.RunModeProd
	RunModeTest RunMode = log.RunModeTest
)

type Server

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

Server 网络服务器

func New

func New(network Network, options ...Option) *Server

New 根据特定网络类型创建一个服务器

Example
package main

import (
	"github.com/kercylan98/minotaur/server"
	"time"
)

func main() {
	srv := server.New(server.NetworkWebsocket,
		server.WithDeadlockDetect(time.Second*5),
		server.WithPProf("/debug/pprof"),
	)

	srv.RegConnectionReceivePacketEvent(func(srv *server.Server, conn *server.Conn, packet server.Packet) {
		conn.Write(packet)
	})

	//go func() { time.Sleep(1 * time.Second); srv.Shutdown() }()
	if err := srv.Run(":9999"); err != nil {
		panic(err)
	}

}
Output:

func (*Server) CloseConn added in v0.0.12

func (slf *Server) CloseConn(id string)

CloseConn 关闭连接

func (*Server) GRPCServer

func (slf *Server) GRPCServer() *grpc.Server

GRPCServer 当网络类型为 NetworkGRPC 时将被允许获取 grpc 服务器,否则将会发生 panic

func (*Server) GetID

func (slf *Server) GetID() int64

GetID 获取服务器id

func (*Server) GetOnline added in v0.0.12

func (slf *Server) GetOnline(id string) *Conn

GetOnline 获取在线连接

func (*Server) GetOnlineAll added in v0.0.12

func (slf *Server) GetOnlineAll() map[string]*Conn

GetOnlineAll 获取所有在线连接

func (*Server) GetOnlineCount added in v0.0.12

func (slf *Server) GetOnlineCount() int

GetOnlineCount 获取在线人数

func (*Server) HttpRouter

func (slf *Server) HttpRouter() gin.IRouter

HttpRouter 当网络类型为 NetworkHttp 时将被允许获取路由器进行路由注册,否则将会发生 panic

func (*Server) IsOnline added in v0.0.12

func (slf *Server) IsOnline(id string) bool

IsOnline 是否在线

func (Server) OnConnectionClosedEvent

func (slf Server) OnConnectionClosedEvent(conn *Conn, err any)

func (Server) OnConnectionOpenedEvent

func (slf Server) OnConnectionOpenedEvent(conn *Conn)

func (Server) OnConnectionReceivePacketEvent

func (slf Server) OnConnectionReceivePacketEvent(conn *Conn, packet Packet)

func (Server) OnConsoleCommandEvent

func (slf Server) OnConsoleCommandEvent(command string)

func (Server) OnMessageErrorEvent

func (slf Server) OnMessageErrorEvent(message *Message, err error)

func (Server) OnMessageLowExecEvent

func (slf Server) OnMessageLowExecEvent(message *Message, cost time.Duration)

func (Server) OnReceiveCrossPacketEvent

func (slf Server) OnReceiveCrossPacketEvent(serverId int64, packet []byte)

func (Server) OnStartBeforeEvent

func (slf Server) OnStartBeforeEvent()

func (Server) OnStartFinishEvent

func (slf Server) OnStartFinishEvent()

func (Server) OnStopEvent added in v0.0.9

func (slf Server) OnStopEvent()

func (Server) RegConnectionClosedEvent

func (slf Server) RegConnectionClosedEvent(handle ConnectionClosedEventHandle)

RegConnectionClosedEvent 在连接关闭后将立刻执行被注册的事件处理函数

func (Server) RegConnectionOpenedEvent

func (slf Server) RegConnectionOpenedEvent(handle ConnectionOpenedEventHandle)

RegConnectionOpenedEvent 在连接打开后将立刻执行被注册的事件处理函数

func (Server) RegConnectionReceivePacketEvent

func (slf Server) RegConnectionReceivePacketEvent(handle ConnectionReceivePacketEventHandle)

RegConnectionReceivePacketEvent 在接收到数据包时将立刻执行被注册的事件处理函数

func (Server) RegConsoleCommandEvent

func (slf Server) RegConsoleCommandEvent(command string, handle ConsoleCommandEventHandle)

RegConsoleCommandEvent 控制台收到指令时将立即执行被注册的事件处理函数

  • 默认将注册 "exit", "quit", "close", "shutdown", "EXIT", "QUIT", "CLOSE", "SHUTDOWN" 指令作为关闭服务器的指令
  • 可通过注册默认指令进行默认行为的覆盖

func (Server) RegMessageErrorEvent

func (slf Server) RegMessageErrorEvent(handle MessageErrorEventHandle)

RegMessageErrorEvent 在处理消息发生错误时将立即执行被注册的事件处理函数

func (Server) RegMessageLowExecEvent

func (slf Server) RegMessageLowExecEvent(handle MessageLowExecEventHandle)

RegMessageLowExecEvent 在处理消息缓慢时将立即执行被注册的事件处理函数

func (Server) RegReceiveCrossPacketEvent

func (slf Server) RegReceiveCrossPacketEvent(handle ReceiveCrossPacketEventHandle)

RegReceiveCrossPacketEvent 在接收到跨服数据包时将立即执行被注册的事件处理函数

func (Server) RegStartBeforeEvent

func (slf Server) RegStartBeforeEvent(handle StartBeforeEventHandle)

RegStartBeforeEvent 在服务器初始化完成启动前立刻执行被注册的事件处理函数

func (Server) RegStartFinishEvent

func (slf Server) RegStartFinishEvent(handle StartFinishEventHandle)

RegStartFinishEvent 在服务器启动完成时将立刻执行被注册的事件处理函数

func (Server) RegStopEvent added in v0.0.9

func (slf Server) RegStopEvent(handle StopEventHandle)

RegStopEvent 服务器停止时将立即执行被注册的事件处理函数

func (*Server) Run

func (slf *Server) Run(addr string) error

Run 使用特定地址运行服务器

server.NetworkTcp (addr:":8888")
server.NetworkTcp4 (addr:":8888")
server.NetworkTcp6 (addr:":8888")
server.NetworkUdp (addr:":8888")
server.NetworkUdp4 (addr:":8888")
server.NetworkUdp6 (addr:":8888")
server.NetworkUnix (addr:"socketPath")
server.NetworkHttp (addr:":8888")
server.NetworkWebsocket (addr:":8888/ws")
server.NetworkKcp (addr:":8888")

func (*Server) Shutdown

func (slf *Server) Shutdown()

Shutdown 主动停止运行服务器

func (*Server) Ticker

func (slf *Server) Ticker() *timer.Ticker

Ticker 获取服务器定时器

type StartBeforeEventHandle

type StartBeforeEventHandle func(srv *Server)

type StartFinishEventHandle

type StartFinishEventHandle func(srv *Server)

type StopEventHandle added in v0.0.9

type StopEventHandle func(srv *Server)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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