Zinx-V0.4

This commit is contained in:
fantasticbin 2025-09-14 14:49:41 +08:00
parent e9a96a95e4
commit 0e6a026d47
4 changed files with 84 additions and 6 deletions

6
zinx/conf/zinx.json Normal file
View File

@ -0,0 +1,6 @@
{
"Name": "zinx demo",
"Host": "127.0.0.1",
"Port": 7777,
"MaxConn": 1000
}

66
zinx/utils/config.go Normal file
View File

@ -0,0 +1,66 @@
package utils
import (
"encoding/json"
"go-study/zinx/ziface"
"os"
"path/filepath"
"runtime"
)
// Config 存储 zinx 框架的全局配置
type Config struct {
// TcpServer 服务器全局对象
TcpServer ziface.IServer
// Host 服务器主机地址
Host string
// TcpPort 服务器端口
TcpPort int
// Name 服务器名称
Name string
// Version 服务器版本号
Version string
// MaxPacketSize 消息的最大包长度
MaxPacketSize uint32
// MaxConn 最大连接数
MaxConn int
}
// ConfigInstance 定义一个全局的配置实例
var ConfigInstance *Config
func (c *Config) Reload() {
// 基于当前源文件目录定位到项目下的 zinx/conf/zinx.json
_, file, _, ok := runtime.Caller(0)
if !ok {
panic("cannot locate current file path")
}
configPath := filepath.Join(filepath.Dir(file), "..", "conf", "zinx.json")
data, err := os.ReadFile(configPath)
if err != nil {
panic(err)
}
// 将 json 文件数据解析到 ConfigInstance 中
err = json.Unmarshal(data, &ConfigInstance)
if err != nil {
panic(err)
}
}
func init() {
// 初始化全局配置,并设置默认值
ConfigInstance = &Config{
Name: "ZinxServerApp",
Version: "V0.4",
Host: "0.0.0.0",
TcpPort: 7777,
MaxConn: 12000,
MaxPacketSize: 4096,
}
// 加载配置文件
ConfigInstance.Reload()
}

View File

@ -2,6 +2,7 @@ package znet
import ( import (
"fmt" "fmt"
"go-study/zinx/utils"
"go-study/zinx/ziface" "go-study/zinx/ziface"
"net" "net"
) )
@ -20,19 +21,24 @@ type Server struct {
} }
// NewServer 创建一个服务器句柄 // NewServer 创建一个服务器句柄
func NewServer(name string) ziface.IServer { func NewServer() ziface.IServer {
utils.ConfigInstance.Reload()
return &Server{ return &Server{
Name: name, Name: utils.ConfigInstance.Name,
IPVersion: "tcp4", IPVersion: "tcp4",
IP: "0.0.0.0", IP: utils.ConfigInstance.Host,
Port: 7777, Port: utils.ConfigInstance.TcpPort,
Router: nil, Router: nil,
} }
} }
// Start 启动服务器 // Start 启动服务器
func (s *Server) Start() { func (s *Server) Start() {
fmt.Printf("[START] Server listenner at IP: %s, Port %d, is starting\n", s.IP, s.Port) fmt.Printf("[START] Server name: %s, listenner at IP: %s, Port %d, is starting\n", s.Name, s.IP, s.Port)
fmt.Printf("[Zinx] Version %s, MaxConn: %d, MaxPacketSize: %d\n",
utils.ConfigInstance.Version,
utils.ConfigInstance.MaxConn,
utils.ConfigInstance.MaxPacketSize)
go func() { go func() {
// 1. 获取一个 TCP 的 Addr // 1. 获取一个 TCP 的 Addr

View File

@ -71,7 +71,7 @@ func ClientTest() {
// TestServer 服务器端测试 // TestServer 服务器端测试
func TestServer(t *testing.T) { func TestServer(t *testing.T) {
// 创建一个 Server 句柄 // 创建一个 Server 句柄
s := NewServer("[Zinx V0.3]") s := NewServer()
// 给当前 Zinx 框架添加一个自定义的 Router // 给当前 Zinx 框架添加一个自定义的 Router
s.AddRouter(&PingRouter{}) s.AddRouter(&PingRouter{})