refactor(rpc): 重构 RPC 客户端并添加重连机制

- 更新了 RPC 客户端的初始化和重连逻辑
- 添加了重连函数和最大重试次数的配置
- 优化了与服务器的连接管理
- 调整了端口相关的数据类型
This commit is contained in:
2025-07-17 05:20:30 +08:00
parent b6231f6eb9
commit bf72b91fc6
18 changed files with 131 additions and 46 deletions

View File

@@ -13,6 +13,7 @@ import (
const rpcaddr = "127.0.0.1:40000"
var clientmap = make(map[uint16]*ClientHandler) //客户端map
var clientidmap = make(map[uint16]uint16) //客户端map
//var usermap = make(map[int]int) //用户->客户端的map
// Define the client handler interface
@@ -45,18 +46,21 @@ func (h *ServerHandler) Kick(ctx context.Context, userid uint32) error {
}
// 注册logic服务器
func (h *ServerHandler) RegisterLogic(ctx context.Context, port uint16) error {
func (h *ServerHandler) RegisterLogic(ctx context.Context, id, port uint16) error {
//TODO 待修复滚动更新可能导致的玩家可以同时在旧服务器和新服务器同时在线的bug
revClient, ok := jsonrpc.ExtractReverseClient[ClientHandler](ctx)
if !ok {
return fmt.Errorf("no reverse client")
}
aa, ok := clientmap[port]
if ok && aa != nil {
aa.QuitSelf(0)
aa, ok := clientidmap[id]
if ok { //如果已经存在且这个端口已经被存过
t := clientmap[aa]
t.QuitSelf(0)
}
clientmap[port] = &revClient
clientidmap[id] = port
return nil
}
@@ -77,21 +81,24 @@ func StartServer() {
var closer jsonrpc.ClientCloser
func StartClient(port uint16, callback any) *struct {
func StartClient(id, port uint16, callback any) *struct {
Kick func(uint32) error
RegisterLogic func(uint16) error
RegisterLogic func(uint16, uint16) error
} {
closer1, err := jsonrpc.NewMergeClient(context.Background(), "ws://"+rpcaddr, "", []interface{}{
&RPCClient,
}, nil, jsonrpc.WithClientHandler("", callback))
closer1, err := jsonrpc.NewMergeClient(context.Background(),
"ws://"+rpcaddr, "", []interface{}{
&RPCClient,
}, nil, jsonrpc.WithClientHandler("", callback),
jsonrpc.WithReconnFun(func() { RPCClient.RegisterLogic(id, port) }),
)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
if port != 0 { //注册logic
RPCClient.RegisterLogic(port)
RPCClient.RegisterLogic(id, port)
}
@@ -110,7 +117,7 @@ func CloseClient() {
var RPCClient struct {
Kick func(uint32) error //踢人
RegisterLogic func(uint16) error //注册服务器消息
RegisterLogic func(uint16, uint16) error
// UserLogin func(int32, int32) error //用户登录事件
// UserLogout func(int32, int32) error //用户登出事件