yyl
2026-02-05 a29fffa93dc66ff45589f8fd1f8584f7bcb9fdad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
using Cysharp.Threading.Tasks;
using System;
using UnityEngine;
 
/// <summary>
/// ClientSocket 适配器 - 将 ClientSocket 适配为 INetworkService 接口
/// (不修改已验证的 ClientSocket 代码)
/// </summary>
public class ClientSocketAdapter : INetworkService
{
    private ClientSocket clientSocket;
    private NetworkState _state = NetworkState.Disconnected;
    
    public NetworkState State
    {
        get => _state;
        private set
        {
            if (_state != value)
            {
                _state = value;
                OnStateChanged?.Invoke(value);
            }
        }
    }
    
    /// <summary>
    /// 是否已连接(适配 ClientSocket.connected)
    /// </summary>
    public bool IsConnected => clientSocket != null && clientSocket.connected;
    
    /// <summary>
    /// 最后收包时间(适配 ClientSocket.lastPackageTime)
    /// </summary>
    public DateTime LastPackageTime => clientSocket?.lastPackageTime ?? DateTime.MinValue;
    
    public event Action<NetworkState> OnStateChanged;
    
    /// <summary>
    /// 构造函数
    /// </summary>
    public ClientSocketAdapter(ServerType type)
    {
        clientSocket = new ClientSocket(type);
        Debug.Log($"[ClientSocketAdapter] 初始化 TCP Socket({type})");
    }
    
    /// <summary>
    /// 连接到 TCP 服务器(适配 ClientSocket.Connect)
    /// </summary>
    public async UniTask<bool> ConnectAsync(string url)
    {
        try
        {
            State = NetworkState.Connecting;
            
            // 解析 URL(支持 "ip:port" 或 "tcp://ip:port")
            string ip;
            int port;
            ParseUrl(url, out ip, out port);
            
            Debug.Log($"[ClientSocketAdapter] 连接 {ip}:{port}");
            
            // 使用 UniTask 包装回调
            var tcs = new UniTaskCompletionSource<bool>();
            
            clientSocket.Connect(ip, port, (success) =>
            {
                if (success)
                {
                    State = NetworkState.Connected;
                    Debug.Log("[ClientSocketAdapter] 连接成功");
                }
                else
                {
                    State = NetworkState.Disconnected;
                    Debug.LogError("[ClientSocketAdapter] 连接失败");
                }
                
                tcs.TrySetResult(success);
            });
            
            return await tcs.Task;
        }
        catch (Exception ex)
        {
            Debug.LogError($"[ClientSocketAdapter] 连接异常: {ex.Message}");
            State = NetworkState.Disconnected;
            return false;
        }
    }
    
    /// <summary>
    /// 断开连接(异步)
    /// </summary>
    public async UniTask DisconnectAsync()
    {
        if (clientSocket != null)
        {
            clientSocket.CloseConnect();
            State = NetworkState.Disconnected;
        }
        await UniTask.CompletedTask;
    }
    
    /// <summary>
    /// 断开连接(同步,适配 ClientSocket.CloseConnect)
    /// </summary>
    public void Disconnect()
    {
        if (clientSocket != null)
        {
            clientSocket.CloseConnect();
            State = NetworkState.Disconnected;
        }
    }
    
    /// <summary>
    /// 发送协议包(适配 ClientSocket.SendInfo)
    /// </summary>
    public void SendInfo(GameNetPackBasic protocol)
    {
        if (!IsConnected)
        {
            Debug.LogError("[ClientSocketAdapter] 未连接,无法发送协议包");
            return;
        }
        
        clientSocket.SendInfo(protocol);
    }
    
    /// <summary>
    /// 发送二进制数据(适配 ClientSocket.SendInfo)
    /// </summary>
    public void SendInfo(byte[] data)
    {
        if (!IsConnected)
        {
            Debug.LogError("[ClientSocketAdapter] 未连接,无法发送数据");
            return;
        }
        
        clientSocket.SendInfo(data);
    }
    
    /// <summary>
    /// 发送二进制数据(异步)
    /// </summary>
    public async UniTask SendAsync(byte[] data)
    {
        SendInfo(data);
        await UniTask.CompletedTask;
    }
    
    /// <summary>
    /// 获取内部的 ClientSocket(兼容性访问)
    /// </summary>
    public ClientSocket GetClientSocket()
    {
        return clientSocket;
    }
    
    /// <summary>
    /// 解析 URL
    /// </summary>
    private void ParseUrl(string url, out string ip, out int port)
    {
        // 默认端口
        port = 8080;
        
        // 移除协议前缀
        if (url.StartsWith("tcp://"))
        {
            url = url.Substring(6);
        }
        
        // 分割 IP 和端口
        var parts = url.Split(':');
        ip = parts[0];
        
        if (parts.Length > 1 && int.TryParse(parts[1], out int parsedPort))
        {
            port = parsedPort;
        }
    }
}