Files
bl/logic/server.go

90 lines
2.2 KiB
Go
Raw Permalink Normal View History

package main
import (
"blazing/common/data/xmlres"
"blazing/common/rpc"
"blazing/common/socket"
"blazing/cool"
"context"
"blazing/logic/controller"
config "blazing/modules/config/service"
"fmt"
"log"
"net"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
const (
minRandomPort = 10000
maxRandomPort = 60000
maxPortRetryCount = 5
)
// determinePort 确定服务器使用的端口
func determinePort(ports []uint32) (int, error) {
// 尝试从指定端口列表中找可用端口最多尝试maxPortRetryCount轮
for i := 0; i < maxPortRetryCount; i++ {
// 遍历指定的端口列表
for _, port := range ports {
if isPortAvailable(port) {
return int(port), nil
}
log.Printf("Port %d is not available, checking next...", port)
}
log.Printf("All candidate ports are in use, retrying round %d...", i+1)
}
return 0, fmt.Errorf("failed to find available port after %d rounds of checking", maxPortRetryCount)
}
// isPortAvailable 检查端口是否可用
func isPortAvailable(port uint32) bool {
address := fmt.Sprintf(":%d", port)
listener, err := net.Listen("tcp", address)
if err != nil {
return false
}
defer listener.Close()
return true
}
// Start 启动服务器
// 如果id是0,那就是login server
func Start() {
serverID := cool.Config.GameOnlineID
cool.Config.ServerInfo = config.NewServerService().GetServerID(serverID).ServerList
2026-02-14 11:51:34 +08:00
// if cool.Config.ServerInfo.IsVip != 0 {
// g.DB().GetCache().SetAdapter(gcache.NewAdapterRedis(cool.Redis)) //设置数据库
// }
go rpc.ListenFight(context.Background())
if cool.Config.ServerInfo.IsDebug == 1 {
g.DB().SetDebug(true)
}
go PprofWeb()
port, err := determinePort(cool.Config.ServerInfo.CanPort)
cool.Config.ServerInfo.Port = uint32(port)
if err != nil {
log.Fatalf("Failed to determine port: %v", err)
}
server := socket.NewServer(
socket.WithCORS(),
socket.WithPort(port),
)
rpcClient := rpc.StartClient(serverID, uint32(port), server) //连接rpc
2026-02-07 22:54:44 +08:00
controller.Maincontroller.RPCClient = rpcClient //将RPC赋值Start
controller.Maincontroller.UID = gconv.Uint32(cool.Config.ServerInfo.GetID()) //赋值服务器ID
controller.Init(true)
xmlres.Initfile()
server.Boot(serverID, gconv.Uint32(port))
}