nets

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README

NETS

多协议 all-in-one 网络框架
一站式启动 TCP / WebSocket / HTTP / KCP 服务,专注路由、连接与生命周期管理
稳定、快速、安全

License Stars

✨ 特性

特性 说明
多协议统一 TCP、WebSocket、HTTP、KCP 四种协议共用路由与连接管理
路由解耦 通过 msgId 绑定消息工厂与业务处理函数,扩展性强
编解码可选 JSON / Protobuf 一键切换,支持自定义 DataPack
连接管理 分片哈希表存储,读写任务三协程分离,属性存取
限流控制 基于 QPS 的连接限流,支持回调与自动断开
优雅退出 监听系统信号,并行关闭所有服务与连接

🔔 环境要求

  • Go ≥ 1.21.1

🚀 快速上手

  1. 安装
go get github.com/451008604/nets
  1. 启动
package main

import (
    "github.com/451008604/nets"
    "github.com/451008604/nets/internal"
    "google.golang.org/protobuf/proto"
)

func main() {
    // 1. 注册路由
    nets.GetInstanceMsgHandler().AddRouter(int32(internal.Test_MsgId_Test_Echo), func() proto.Message { return &internal.Test_EchoRequest{} }, func(conn nets.IConnection, message proto.Message) {
        // 获取请求数据
        msgReq, _ := message.(*internal.Test_EchoRequest)
        // 构造响应数据
        msgRes := &internal.Test_EchoResponse{}
        // 业务处理完毕发送响应数据
        defer conn.SendMsg(int32(internal.Test_MsgId_Test_Echo), msgRes)

        // ...处理逻辑,并设置响应数据...
        msgRes.Message = msgReq.GetMessage()
    })

    // 2. 启动服务(阻塞主协程) 
    nets.GetInstanceServerManager().RegisterServer(nets.GetServerHTTP(), nets.GetServerKCP(), nets.GetServerTCP(), nets.GetServerWS())
}
  1. 详细用法参考

🔧 分布式压测

性能测试工具位于 test 目录,采用 docker compose 编排 1个server + N个client 模拟海量客户端并发测试。具体测试配置项位于 docker-compose.yml
进入 test 目录,执行 sh ./start.sh 启动性能测试


📄 许可证

Apache-2.0 License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ConnPropertyHttpAuthorization = "HttpAuthorization"
	ConnPropertyHttpReader        = "HttpReader"
	ConnPropertyHttpWriter        = "HttpWriter"
)

Functions

func GenerateConnID added in v1.2.2

func GenerateConnID() string

func PutMessage added in v1.2.2

func PutMessage(m IMessage)

func SetCustomServer

func SetCustomServer(custom *CustomServer)

设置自定义服务器参数

Types

type AppConf

type AppConf struct {
	AppName          string     // 服务名称
	MaxPackSize      int        // 数据包最大长度
	MaxConn          int        // 最大允许连接数
	WorkerTaskMaxLen int        // 每个工作队列可执行最大任务数量
	MaxMsgChanLen    int        // 读写通道最大限度
	MaxFlowSecond    int        // 每秒允许的最大请求数量
	ProtocolIsJson   bool       // 是否使用json协议
	ConnRWTimeOut    int        // 连接读写超时时间(秒)
	ServerTCP        ServerConf // tcp服务
	ServerWS         ServerConf // websocket服务
	ServerHTTP       ServerConf // http服务
	ServerKCP        ServerConf // http服务
}

func GetServerConf

func GetServerConf() *AppConf

获取默认配置

type BaseRouter

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

func (*BaseRouter) GetNewMsg

func (b *BaseRouter) GetNewMsg() proto.Message

func (*BaseRouter) RunHandler

func (b *BaseRouter) RunHandler(conn IConnection, message proto.Message)

func (*BaseRouter) SetHandler

func (b *BaseRouter) SetHandler(msgHandler IReceiveMsgHandler)

func (*BaseRouter) SetMsg

func (b *BaseRouter) SetMsg(msgTemplate INewMsgStructTemplate)

type ConnectionBase

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

func (*ConnectionBase) ByteToProtocol

func (c *ConnectionBase) ByteToProtocol(byte []byte, target proto.Message) error

func (*ConnectionBase) Close added in v1.2.2

func (c *ConnectionBase) Close()

func (*ConnectionBase) ConnCtxDone added in v1.2.2

func (c *ConnectionBase) ConnCtxDone() <-chan struct{}

func (*ConnectionBase) DoTask

func (c *ConnectionBase) DoTask(task func())

func (*ConnectionBase) FlowControl

func (c *ConnectionBase) FlowControl() (b bool)

func (*ConnectionBase) GetConnId

func (c *ConnectionBase) GetConnId() string

func (*ConnectionBase) GetProperty

func (c *ConnectionBase) GetProperty(key string) any

func (*ConnectionBase) IsClose

func (c *ConnectionBase) IsClose() bool

func (*ConnectionBase) Open added in v1.2.2

func (c *ConnectionBase) Open()

func (*ConnectionBase) ProtocolToByte

func (c *ConnectionBase) ProtocolToByte(str proto.Message) []byte

func (*ConnectionBase) RemoteAddrStr added in v1.2.2

func (c *ConnectionBase) RemoteAddrStr() string

func (*ConnectionBase) RemoveProperty added in v1.2.2

func (c *ConnectionBase) RemoveProperty(key string)

func (*ConnectionBase) SendMsg

func (c *ConnectionBase) SendMsg(msgId int32, msgData proto.Message)

func (*ConnectionBase) SetProperty added in v1.2.2

func (c *ConnectionBase) SetProperty(key string, value any)

type ConnectionManager

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

func GetInstanceConnManager

func GetInstanceConnManager() *ConnectionManager

连接管理器

func (*ConnectionManager) Add

func (c *ConnectionManager) Add(conn IConnection)

func (*ConnectionManager) ClearConn

func (c *ConnectionManager) ClearConn()

func (*ConnectionManager) ConnRateLimiting

func (c *ConnectionManager) ConnRateLimiting(conn IConnection)

func (*ConnectionManager) Get

func (c *ConnectionManager) Get(connId string) (IConnection, bool)

func (*ConnectionManager) GetConnClosed added in v1.2.2

func (c *ConnectionManager) GetConnClosed(conn IConnection)

func (*ConnectionManager) GetConnOpened added in v1.2.2

func (c *ConnectionManager) GetConnOpened(conn IConnection)

func (*ConnectionManager) Len

func (c *ConnectionManager) Len() int

func (*ConnectionManager) RangeConnections

func (c *ConnectionManager) RangeConnections(handler func(conn IConnection))

func (*ConnectionManager) Remove

func (c *ConnectionManager) Remove(conn IConnection)

func (*ConnectionManager) SetConnClosed added in v1.2.2

func (c *ConnectionManager) SetConnClosed(connCloseCallBack func(conn IConnection))

func (*ConnectionManager) SetConnOnRateLimiting

func (c *ConnectionManager) SetConnOnRateLimiting(limitCallBack func(conn IConnection))

func (*ConnectionManager) SetConnOpened added in v1.2.2

func (c *ConnectionManager) SetConnOpened(connOpenCallBack func(conn IConnection))

type CustomServer

type CustomServer struct {
	AppConf  *AppConf  // 服务启动配置
	DataPack IDataPack // 自定义编码/解码器
}

自定义服务器

type IConnection

type IConnection interface {
	// 启动连接(通过connmanager调用)
	Open()
	// 停止连接(通过connmanager调用)
	Close()

	// 获取真实连接
	GetNetConn() net.Conn
	// 连接上下文关闭信号
	ConnCtxDone() <-chan struct{}

	// 启动接收消息协程
	StartReader() bool
	// 启动发送消息协程
	StartWriter(data []byte) bool
	// 执行任务
	DoTask(task func())

	// 获取当前连接Id
	GetConnId() string
	// 获取客户端地址信息
	RemoteAddrStr() string
	// 获取连接是否已关闭
	IsClose() bool
	// 获取连接绑定的属性
	GetProperty(key string) any
	// 设置连接绑定的属性
	SetProperty(key string, value any)
	// 移除连接绑定的属性
	RemoveProperty(key string)

	// 发送消息给客户端
	SendMsg(msgId int32, msgData proto.Message)

	// 限流控制
	FlowControl() bool

	// 序列化
	ProtocolToByte(str proto.Message) []byte
	// 反序列化
	ByteToProtocol(byte []byte, target proto.Message) error
}

func NewConnectionHTTP

func NewConnectionHTTP(server IServer, writer http.ResponseWriter, reader *http.Request) IConnection

func NewConnectionKCP

func NewConnectionKCP(server *serverKCP, conn net.Conn) IConnection

func NewConnectionTCP

func NewConnectionTCP(server IServer, conn *net.TCPConn) IConnection

func NewConnectionWS

func NewConnectionWS(server IServer, conn *websocket.Conn) IConnection

type IDataPack

type IDataPack interface {
	// 获取消息头长度
	GetHeadLen() int
	// 消息封包
	Pack(msg IMessage) []byte
	// 消息拆包
	UnPack([]byte) IMessage
}

封包拆包,通过固定的包头获取消息数据,解决TCP粘包问题

func NewDataPack

func NewDataPack() IDataPack

type IErrCapture

type IErrCapture func(conn IConnection, panicInfo string)

type IFilter

type IFilter func(conn IConnection, msg IMessage) bool

type IMessage

type IMessage interface {
	// 获取消息Id
	GetMsgId() uint16
	// 获取消息长度
	GetDataLen() uint16
	// 获取消息内容
	GetData() []byte
	// 设置消息内容
	SetData([]byte)
}

定义消息模板

type INewMsgStructTemplate

type INewMsgStructTemplate func() proto.Message

type IReceiveMsgHandler

type IReceiveMsgHandler func(conn IConnection, message proto.Message)

type IServer

type IServer interface {
	// 获取服务器名称
	GetServerName() string
	// 启动服务器
	Start()
}

定义服务器接口

func GetServerHTTP

func GetServerHTTP() IServer

func GetServerKCP

func GetServerKCP() IServer

func GetServerTCP

func GetServerTCP() IServer

func GetServerWS

func GetServerWS() IServer

type Message

type Message struct {
	proto.Message `json:"-"`
	Id            uint16 `protobuf:"bytes,1,opt,name=msg_id,proto3" json:"msg_id"` // 消息Id
	Data          []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data"`     // 消息内容
	DataLen       uint16 `json:"-"`                                                // 消息长度
}

func GetMessage added in v1.2.2

func GetMessage() *Message

func (*Message) GetData

func (m *Message) GetData() []byte

func (*Message) GetDataLen

func (m *Message) GetDataLen() uint16

func (*Message) GetMsgId

func (m *Message) GetMsgId() uint16

func (*Message) SetData

func (m *Message) SetData(bytes []byte)

type MsgHandler

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

func GetInstanceMsgHandler

func GetInstanceMsgHandler() *MsgHandler

消息处理器

func (*MsgHandler) AddRouter

func (m *MsgHandler) AddRouter(msgId int32, msgTemplate INewMsgStructTemplate, msgHandler IReceiveMsgHandler)

func (*MsgHandler) GetApis

func (m *MsgHandler) GetApis() map[int32]*BaseRouter

func (*MsgHandler) GetErrCapture

func (m *MsgHandler) GetErrCapture(conn IConnection)

func (*MsgHandler) GetFilter

func (m *MsgHandler) GetFilter() IFilter

func (*MsgHandler) SetErrCapture

func (m *MsgHandler) SetErrCapture(fun IErrCapture)

func (*MsgHandler) SetFilter

func (m *MsgHandler) SetFilter(fun IFilter)

type ServerConf

type ServerConf struct {
	Address     string // IP地址
	Port        int    // 端口
	TLSCertPath string // ssl证书路径
	TLSKeyPath  string // ssl密钥路径
}

type ServerManager

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

func GetInstanceServerManager

func GetInstanceServerManager() *ServerManager

服务管理器

func (*ServerManager) IsClose

func (c *ServerManager) IsClose() bool

func (*ServerManager) RegisterServer

func (c *ServerManager) RegisterServer(server ...IServer)

func (*ServerManager) StopAll

func (c *ServerManager) StopAll()

func (*ServerManager) WaitGroupAdd

func (c *ServerManager) WaitGroupAdd(delta int)

func (*ServerManager) WaitGroupDone

func (c *ServerManager) WaitGroupDone()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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