From 18e418ca0b5354d464f242be08958b90ee8d779a Mon Sep 17 00:00:00 2001
From: yyl <yyl>
Date: 星期五, 06 二月 2026 14:59:24 +0800
Subject: [PATCH] TCP/WEBSOCKET SUPPORT
---
/dev/null | 11 -
Main/Core/NetworkPackage/Socket/ClientSocket.cs | 397 ++++++++++++++++++++++++++++++++-------
Main/Main.cs | 2
Main/Core/NetworkPackage/GameNetSystem.cs | 179 +++--------------
4 files changed, 364 insertions(+), 225 deletions(-)
diff --git a/Main/Core/NetworkPackage/ClientSocketAdapter.cs b/Main/Core/NetworkPackage/ClientSocketAdapter.cs
deleted file mode 100644
index 45996c7..0000000
--- a/Main/Core/NetworkPackage/ClientSocketAdapter.cs
+++ /dev/null
@@ -1,186 +0,0 @@
-using Cysharp.Threading.Tasks;
-using System;
-using UnityEngine;
-
-/// <summary>
-/// ClientSocket 閫傞厤鍣� - 灏� ClientSocket 閫傞厤涓� INetworkService 鎺ュ彛
-/// 锛堜笉淇敼宸查獙璇佺殑 ClientSocket 浠g爜锛�
-/// </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;
-
- // 瑙f瀽 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>
- /// 瑙f瀽 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;
- }
- }
-}
diff --git a/Main/Core/NetworkPackage/ClientSocketAdapter.cs.meta b/Main/Core/NetworkPackage/ClientSocketAdapter.cs.meta
deleted file mode 100644
index 98e1b23..0000000
--- a/Main/Core/NetworkPackage/ClientSocketAdapter.cs.meta
+++ /dev/null
@@ -1,11 +0,0 @@
-fileFormatVersion: 2
-guid: 529c690109d07de41aa851e793469e7d
-MonoImporter:
- externalObjects: {}
- serializedVersion: 2
- defaultReferences: []
- executionOrder: 0
- icon: {instanceID: 0}
- userData:
- assetBundleName:
- assetBundleVariant:
diff --git a/Main/Core/NetworkPackage/GameNetSystem.cs b/Main/Core/NetworkPackage/GameNetSystem.cs
index 7bbd6e3..94d9e5e 100644
--- a/Main/Core/NetworkPackage/GameNetSystem.cs
+++ b/Main/Core/NetworkPackage/GameNetSystem.cs
@@ -2,24 +2,14 @@
using System;
using System.Collections;
using System.Collections.Generic;
-using Cysharp.Threading.Tasks;
-public enum NetworkType
-{
- TCP, // 浣跨敤鍘熸湁鐨� TCP Socket
- WebSocket // 浣跨敤 WebSocket锛堝皬娓告垙骞冲彴锛�
-}
public class GameNetSystem : Singleton<GameNetSystem>
{
//闄愬埗瀹㈡埛绔殑涓嬩竴涓寘鏄櫥褰曞寘C0101_tagCPlayerLogin锛屽鏋滀笉鏄櫥褰曞寘涓嶅厑璁稿彂閫�
bool waitLogin = false; //绛夊緟鍙戦�佺櫥褰曞寘锛屽鏋滄湁鍏朵粬鍖呯洿鎺ュ睆钄斤紝閬垮厤鏂嚎閲嶈繛鐨勬儏鍐靛彂浜嗘敾鍑诲寘涔嬬被鐨�
//绛夊緟鏈嶅姟绔�0403鐨勫寘鍚庢墠鑳藉彂鍏朵粬鐨勫姛鑳藉寘锛屽彧鏈塁0123_tagCClientPackVersion 鍜� C0101_tagCPlayerLogin 鍙互鍙戦��
- bool waitLoginMap = false;
-
- // 缃戠粶鏈嶅姟鎺ュ彛锛堢粺涓�鏀寔 TCP 鍜� WebSocket锛�
- private INetworkService networkService;
-
+ bool waitLoginMap = false;
NetUpdateBehaviour m_NetUpdateBehaviour;
NeverConnectState neverConnectState;
AccountLoginState accountLoginState;
@@ -84,26 +74,12 @@
}
}
- private ClientSocket mainSocket; // 淇濈暀鍏煎锛屼絾涓嶅啀鐩存帴浣跨敤
-
- public bool mainSocketConnected
- {
- get { return networkService?.IsConnected ?? false; }
- }
+ private ClientSocket mainSocket;
+ public bool mainSocketConnected { get { return mainSocket == null ? false : mainSocket.connected; } }
public float timeSinceMainSocketLastProtocol
{
- get
- {
- if (networkService == null)
- return Time.time;
-
- var lastTime = networkService.LastPackageTime;
- if (lastTime == DateTime.MinValue)
- return Time.time; // 浠庢湭鏀跺寘
-
- return (float)(DateTime.Now - lastTime).TotalSeconds;
- }
+ get { return mainSocket == null ? Time.time : (float)(DateTime.Now - mainSocket.lastPackageTime).TotalSeconds; }
}
@@ -131,9 +107,9 @@
{
try
{
- if (networkService != null && networkService.IsConnected)
+ if (mainSocketConnected)
{
- networkService.Disconnect();
+ mainSocket.CloseConnect();
}
}
catch (System.Exception ex)
@@ -141,98 +117,22 @@
Debug.Log(ex);
}
- mainProtocolQueue.Clear();
-
- // 鏍规嵁 Main.CurrentNetworkType 閫夋嫨缃戠粶绫诲瀷
- Debug.Log($"[GameNetSystem] 杩炴帴鏈嶅姟鍣� {ip}:{port}锛屼娇鐢▄(Main.CurrentNetworkType == NetworkType.WebSocket ? "WebSocket" : "TCP")}");
-
- if (Main.CurrentNetworkType == NetworkType.WebSocket)
- {
- // 浣跨敤 WebSocket
- ConnectWithWebSocket(ip, port, onConnected);
- }
- else
- {
- // 浣跨敤 TCP Socket锛堥�氳繃閫傞厤鍣級
- ConnectWithTCP(ip, port, onConnected);
- }
- }
-
- private async void ConnectWithTCP(string ip, int port, Action<bool> onConnected)
- {
- try
- {
- // 鍒涘缓 TCP Socket 閫傞厤鍣紙涓嶄慨鏀� ClientSocket锛�
- networkService = new ClientSocketAdapter(ServerType.Main);
-
- // 璁㈤槄鐘舵�佷簨浠�
- networkService.OnStateChanged += OnNetworkStateChanged;
-
- // 杩炴帴
- string url = $"{ip}:{port}";
- Debug.Log($"[GameNetSystem] TCP 寮�濮嬭繛鎺�: {url}");
- bool success = await networkService.ConnectAsync(url);
-
- Debug.Log($"[GameNetSystem] TCP 杩炴帴{(success ? "鎴愬姛" : "澶辫触")}: {url}");
-
- // 鍏煎锛氫繚鐣� mainSocket 寮曠敤锛堜絾閫氳繃 networkService 璁块棶锛�
- mainSocket = (networkService as ClientSocketAdapter)?.GetClientSocket();
-
- if (onConnected != null)
- {
- onConnected(success);
- }
- }
- catch (System.Exception ex)
- {
- Debug.LogError($"[GameNetSystem] TCP 杩炴帴寮傚父: {ex.Message}");
- if (onConnected != null)
- {
- onConnected(false);
- }
- }
- }
-
- private async void ConnectWithWebSocket(string ip, int port, Action<bool> onConnected)
- {
- try
- {
- // 鍒涘缓 WebSocket 鏈嶅姟锛堜紶鍏� ServerType锛屼笌 ClientSocket 涓�鑷达級
- networkService = new WebSocketNetworkService(ServerType.Main);
-
- // 璁㈤槄鐘舵�佷簨浠�
- networkService.OnStateChanged += OnNetworkStateChanged;
-
- string url = $"ws://{ip}:{port}";
- Debug.Log($"[GameNetSystem] WebSocket 寮�濮嬭繛鎺�: {url}");
- bool success = await networkService.ConnectAsync(url);
-
- Debug.Log($"[GameNetSystem] WebSocket 杩炴帴{(success ? "鎴愬姛" : "澶辫触")}: {url}");
-
- if (onConnected != null)
- {
- onConnected(success);
- }
- }
- catch (System.Exception ex)
- {
- Debug.LogError($"[GameNetSystem] WebSocket 杩炴帴寮傚父: {ex.Message}");
- if (onConnected != null)
- {
- onConnected(false);
- }
- }
- }
-
- private void OnNetworkStateChanged(NetworkState state)
- {
- Debug.Log($"[GameNetSystem] 缃戠粶鐘舵�佸彉鍖�: {state}");
-
- // 鏂紑杩炴帴鏃惰Е鍙戞柇绾垮鐞�
- if (state == NetworkState.Disconnected || state == NetworkState.Closed)
+ mainSocket = new ClientSocket(ServerType.Main);
+ // websocket鐨勬柇寮�閾炬帴闇�瑕佸鐞嗕竴涓�
+ mainSocket.OnDisconnected = () =>
{
netState = NetState.DisConnected;
- }
+ LoginManager.Instance.busy = false;
+ };
+ mainProtocolQueue.Clear();
+
+ mainSocket.Connect(ip, port, (bool ok) =>
+ {
+ if (onConnected != null)
+ {
+ onConnected(ok);
+ }
+ });
}
//闄愬埗瀹㈡埛绔殑涓嬩竴涓寘鏄櫥褰曞寘C0101_tagCPlayerLogin锛屽鏋滀笉鏄櫥褰曞寘涓嶅厑璁稿彂閫�
@@ -258,17 +158,18 @@
public void SendCachePackage()
{
int cnt = sendQueue.Count;
- while (sendQueue.Count > 0)
+ if (mainSocket != null)
{
- SendInfo(sendQueue.Dequeue());
+ while (sendQueue.Count > 0)
+ {
+ SendInfo(sendQueue.Dequeue());
+ }
}
- Debug.Log($"閲嶇偣鎻愰啋锛�0403鐧诲綍鍚� 鍙戦�佺紦瀛樺寘鏁伴噺 {cnt} 涓�");
+ Debug.LogError($"閲嶇偣鎻愰啋锛�0403鐧诲綍鍚� 鍙戦�佺紦瀛樺寘鏁伴噺 {cnt} 涓�");
}
public void SendInfo(GameNetPackBasic protocol)
{
- Debug.LogError("protocol to send: " + protocol.ToString());
-
if (waitLogin)
{
if (protocol is not C0101_tagCPlayerLogin)
@@ -289,21 +190,22 @@
}
}
- if (networkService != null)
+ if (mainSocket != null)
{
- networkService.SendInfo(protocol);
+ mainSocket.SendInfo(protocol);
DebugPkgCache.Push(protocol);
}
}
+#if UNITY_EDITOR
public void SendInfo(byte[] vBytes)
{
- if (networkService != null)
+ if (mainSocket != null)
{
- networkService.SendInfo(vBytes);
+ mainSocket.SendInfo(vBytes);
}
}
-
+#endif
public void PushPackage(GameNetPackBasic protocol, ServerType type)
{
@@ -331,9 +233,9 @@
{
try
{
- if (networkService != null)
+ if (mainSocket != null)
{
- networkService.Disconnect();
+ mainSocket.CloseConnect();
}
mainProtocolQueue.Clear();
@@ -355,9 +257,9 @@
{
try
{
- if (networkService != null)
+ if (mainSocket != null)
{
- networkService.Disconnect();
+ mainSocket.CloseConnect();
}
mainProtocolQueue.Clear();
@@ -380,9 +282,9 @@
{
SDKUtils.Instance.RoleLoginOut();
- if (networkService != null)
+ if (mainSocket != null)
{
- networkService.Disconnect();
+ mainSocket.CloseConnect();
}
mainProtocolQueue.Clear();
@@ -414,10 +316,7 @@
void OnUpdate()
{
- if (networkService != null)
- {
- if (networkService is WebSocketNetworkService wsService) { wsService.Update(); }
- }
+ mainSocket?.DispatchMessageQueue();
lock (this)
{
diff --git a/Main/Core/NetworkPackage/INetworkService.cs b/Main/Core/NetworkPackage/INetworkService.cs
deleted file mode 100644
index f75d5da..0000000
--- a/Main/Core/NetworkPackage/INetworkService.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-using Cysharp.Threading.Tasks;
-using System;
-
-/// <summary>
-/// 缃戠粶鏈嶅姟鎺ュ彛 - 缁熶竴灏佽 Socket 鍜� WebSocket锛堥�傞厤 ClientSocket API锛�
-/// </summary>
-public interface INetworkService
-{
- /// <summary>
- /// 缃戠粶杩炴帴鐘舵��
- /// </summary>
- NetworkState State { get; }
-
- /// <summary>
- /// 鏄惁宸茶繛鎺ワ紙閫傞厤 ClientSocket.connected锛�
- /// </summary>
- bool IsConnected { get; }
-
- /// <summary>
- /// 鏈�鍚庢敹鍖呮椂闂达紙閫傞厤 ClientSocket.lastPackageTime锛�
- /// </summary>
- System.DateTime LastPackageTime { get; }
-
- /// <summary>
- /// 杩炴帴鍒版湇鍔″櫒
- /// </summary>
- /// <param name="url">鏈嶅姟鍣ㄥ湴鍧�锛坵s:// 鎴� wss:// 瀵逛簬 WebSocket锛�</param>
- UniTask<bool> ConnectAsync(string url);
-
- /// <summary>
- /// 鏂紑杩炴帴锛堝紓姝ワ級
- /// </summary>
- UniTask DisconnectAsync();
-
- /// <summary>
- /// 鏂紑杩炴帴锛堝悓姝ワ紝閫傞厤 ClientSocket.CloseConnect锛�
- /// </summary>
- void Disconnect();
-
- /// <summary>
- /// 鍙戦�佸崗璁寘锛堥�傞厤 ClientSocket.SendInfo锛�
- /// </summary>
- void SendInfo(GameNetPackBasic protocol);
-
- /// <summary>
- /// 鍙戦�佷簩杩涘埗鏁版嵁锛堥�傞厤 ClientSocket.SendInfo锛�
- /// </summary>
- void SendInfo(byte[] data);
-
- /// <summary>
- /// 鍙戦�佷簩杩涘埗鏁版嵁锛堝紓姝ワ級
- /// </summary>
- UniTask SendAsync(byte[] data);
-
- /// <summary>
- /// 杩炴帴鐘舵�佹敼鍙樹簨浠�
- /// </summary>
- event Action<NetworkState> OnStateChanged;
-}
-
-/// <summary>
-/// 缃戠粶杩炴帴鐘舵��
-/// </summary>
-public enum NetworkState
-{
- Disconnected, // 鏈繛鎺�
- Connecting, // 杩炴帴涓�
- Connected, // 宸茶繛鎺�
- Reconnecting, // 閲嶈繛涓�
- Closed // 宸插叧闂�
-}
diff --git a/Main/Core/NetworkPackage/INetworkService.cs.meta b/Main/Core/NetworkPackage/INetworkService.cs.meta
deleted file mode 100644
index 2de0088..0000000
--- a/Main/Core/NetworkPackage/INetworkService.cs.meta
+++ /dev/null
@@ -1,11 +0,0 @@
-fileFormatVersion: 2
-guid: 74d34d5ef1dcb5e4bae375bc3dd8cd41
-MonoImporter:
- externalObjects: {}
- serializedVersion: 2
- defaultReferences: []
- executionOrder: 0
- icon: {instanceID: 0}
- userData:
- assetBundleName:
- assetBundleVariant:
diff --git a/Main/Core/NetworkPackage/Network.meta b/Main/Core/NetworkPackage/Network.meta
deleted file mode 100644
index 9fc19a6..0000000
--- a/Main/Core/NetworkPackage/Network.meta
+++ /dev/null
@@ -1,8 +0,0 @@
-fileFormatVersion: 2
-guid: 683353faee5b8104da00dafdc791bbed
-folderAsset: yes
-DefaultImporter:
- externalObjects: {}
- userData:
- assetBundleName:
- assetBundleVariant:
diff --git a/Main/Core/NetworkPackage/Socket/ClientSocket.cs b/Main/Core/NetworkPackage/Socket/ClientSocket.cs
index 3055fe0..bf072a0 100644
--- a/Main/Core/NetworkPackage/Socket/ClientSocket.cs
+++ b/Main/Core/NetworkPackage/Socket/ClientSocket.cs
@@ -1,39 +1,73 @@
锘縰sing UnityEngine;
using System;
-using System.Collections;
using System.Collections.Generic;
+
+#if !UNITY_WEBGL && !H5_VERSION
using System.Net;
using System.Net.Sockets;
using System.Threading;
+#else
+using NativeWebSocket;
+using Cysharp.Threading.Tasks;
+#endif
+/// <summary>
+/// 缁熶竴鐨勭綉缁淪ocket绫� - 鑷姩閫傞厤TCP Socket鍜學ebSocket
+/// TCP Socket: Windows, Mac, iOS, Android绛夊钩鍙�
+/// WebSocket: WebGL/寰俊灏忔父鎴忕瓑Web骞冲彴
+/// </summary>
public class ClientSocket
{
GameNetEncode encoder = new GameNetEncode();
+
+#if !UNITY_WEBGL && !H5_VERSION
+ // TCP Socket 瀹炵幇锛堥潪WebGL骞冲彴锛�
Socket m_Socket;
public Socket socket { get { return m_Socket; } }
-
private Thread m_packageThread;
- private byte[] bufferBytes = new byte[4096]; // 4K锛屽崟鍖呭瓧鑺傛暟缁勭紦瀛�
- private byte[] fragmentBytes; //鐣欏寘鍚庣殑鍐呭
- private long getBytesTotal = 0; //鍙戦�佺殑鏁版嵁鎬婚噺
- private long sendBytesTotal = 0; //鍙戦�佺殑鏁版嵁鎬婚噺
+ private byte[] bufferBytes = new byte[4096];
+ private byte[] fragmentBytes; // TCP鍒嗗寘缂撳瓨
+ bool isStopTreading = false;
+#else
+ // WebSocket 瀹炵幇锛圵ebGL骞冲彴锛�
+ WebSocket webSocket;
+ public WebSocket socket { get { return webSocket; } }
+#endif
- public bool connected { get { return m_Socket == null ? false : m_Socket.Connected; } }
+ public Action OnDisconnected;
+
+ private long getBytesTotal = 0;
+ private long sendBytesTotal = 0;
+
+ public bool connected
+ {
+ get
+ {
+#if !UNITY_WEBGL && !H5_VERSION
+ return m_Socket == null ? false : m_Socket.Connected;
+#else
+ return webSocket != null && webSocket.State == WebSocketState.Open;
+#endif
+ }
+ }
ServerType socketType = ServerType.Main;
DateTime m_LastPackageTime;
public DateTime lastPackageTime { get { return m_LastPackageTime; } }
- bool isStopTreading = false;
-
string ip;
int port;
Action<bool> onConnected = null;
+ Queue<byte[]> sendQueue = new Queue<byte[]>();
+ static byte[] vCmdBytes = new byte[2];
public ClientSocket(ServerType type)
{
this.socketType = type;
}
+
+#if !UNITY_WEBGL && !H5_VERSION
+ // ==================== TCP Socket 瀹炵幇 ====================
public void Connect(string _ip, int _port, Action<bool> _onConnected)
{
@@ -260,7 +294,6 @@
}
- static byte[] vCmdBytes = new byte[2];
/// <summary>
/// 瑙f瀽鏁版嵁鍖咃細 FFCC+灏佸寘闀垮害+灏佸寘锛堝皝鍖呭ご+鏁版嵁锛夌粨鏋勪綋鍐呭
/// </summary>
@@ -346,71 +379,14 @@
}
- /// <summary>
- /// 鍙戦�佷俊鎭�
- /// </summary>
- public void SendInfo(GameNetPackBasic protocol)
- {
- if (!connected)
- {
- return;
- }
-
- if (protocol == null)
- {
- Debug.LogError("瑕佸彂鐨勪俊鎭璞′负绌�");
- return;
- }
-
- // if (Launch.Instance.EnableNetLog)
- // {
- // Debug.LogFormat("鍙戝寘锛歿0}", protocol.GetType().Name);
- // }
-
- if (protocol.combineBytes == null)
- {
- protocol.WriteToBytes();
- }
- protocol.CombineDatas(encoder);
-#if UNITY_EDITOR
- NetPkgCtl.RecordPackage(socketType, protocol.vInfoCont, NetPackagetType.Client, protocol.ToString(), FieldPrint.PrintFields(protocol), FieldPrint.PrintFieldsExpand(protocol, true));
-#endif
- sendBytesTotal += protocol.combineBytes.Length;
- SendBytes(protocol.combineBytes);
- }
-
- /// <summary>
- /// 鍙戦�佷俊鎭�
- /// </summary>
- /// <param name="vBytes"></param>
- public void SendInfo(byte[] vBytes)
- {
- if (!connected)
- {
- Debug.LogError("灏氭湭涓庤鍚庣閾炬帴锛佹棤娉曞彂閫佷俊鎭�");
- return;
- }
-
- if (vBytes == null || vBytes.Length < 2)
- {
- Debug.LogError("瑕佸彂鐨勪俊鎭暟鎹负绌烘垨鏁版嵁涓嶈冻");
- return;
- }
-
- vBytes = encoder.BaseXorAdd(vBytes);
- byte[] vFrameHead = new byte[] { 255, 204 };
- byte[] vMsgBodyLength = BitConverter.GetBytes(vBytes.Length);
- byte[] vTotal = new byte[vBytes.Length + 6];
- Array.Copy(vFrameHead, 0, vTotal, 0, vFrameHead.Length);
- Array.Copy(vMsgBodyLength, 0, vTotal, 2, vMsgBodyLength.Length);
- Array.Copy(vBytes, 0, vTotal, 6, vBytes.Length);
-
- SendBytes(vTotal);
- }
-
- Queue<byte[]> sendQueue = new Queue<byte[]>();
+ // TCP Socket 鐨� SendBytes锛堢鏈夋柟娉曪紝鐢辩粺涓�鐨� SendInfo 璋冪敤锛�
private void SendBytes(byte[] bytes)
{
+ // 璋冭瘯鏃ュ織锛氳緭鍑哄彂閫佺殑瀛楄妭鏁版嵁
+ // string hexString = "[TCP] SendBytes Length=" + bytes.Length + " Data=" + BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 32)).Replace("-", " ");
+ // if (bytes.Length > 32) hexString += "...";
+ // Debug.Log(hexString);
+
try
{
if (sendQueue.Count > 0)
@@ -448,4 +424,279 @@
}
}
+ public void DispatchMessageQueue()
+ {
+ // TCP涓嶉渶瑕佽疆璇�
+ }
+
+#else
+ // ==================== WebSocket 瀹炵幇锛圵ebGL骞冲彴锛�====================
+
+ public async void Connect(string _ip, int _port, Action<bool> _onConnected)
+ {
+ ip = _ip;
+ port = _port;
+ onConnected = _onConnected;
+
+ string url = $"ws://{_ip}:{_port}";
+ Debug.Log($"[ClientSocket-WebSocket] 寮�濮嬭繛鎺�: {url}");
+
+ try
+ {
+ webSocket = new WebSocket(url);
+
+ // 娉ㄥ唽WebSocket鍥炶皟
+ webSocket.OnOpen += OnWebSocketOpen;
+ webSocket.OnMessage += OnWebSocketMessage;
+ webSocket.OnError += OnWebSocketError;
+ webSocket.OnClose += OnWebSocketClose;
+
+ await webSocket.Connect();
+ }
+ catch (Exception ex)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 杩炴帴寮傚父: {ex.Message}");
+ if (onConnected != null)
+ {
+ onConnected(false);
+ onConnected = null;
+ }
+ }
+ }
+
+ private void OnWebSocketOpen()
+ {
+ Debug.Log("[ClientSocket-WebSocket] 杩炴帴鎴愬姛");
+ m_LastPackageTime = DateTime.Now;
+
+ if (onConnected != null)
+ {
+ onConnected(true);
+ onConnected = null;
+ }
+ }
+
+ private void OnWebSocketMessage(byte[] data)
+ {
+ try
+ {
+ getBytesTotal += data.Length;
+
+ // WebSocket鏄秷鎭ā寮忥紝姣忔鏀跺埌瀹屾暣鍖咃紝鐩存帴澶勭悊
+ byte[] fixBytes = data;
+ int vReadIndex = 0;
+ byte[] vPackBytes;
+ int vLeavingLeng = 0;
+ int vBodyLeng = 0;
+ int vTotalLeng = fixBytes.Length;
+ GameNetPackBasic vNetpack;
+
+ while (vReadIndex < vTotalLeng)
+ {
+ vLeavingLeng = vTotalLeng - vReadIndex;
+ if (vLeavingLeng < 6)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 鍖呮暟鎹笉瓒�: {vLeavingLeng} bytes");
+ break;
+ }
+
+ vBodyLeng = BitConverter.ToInt32(fixBytes, vReadIndex + 2);
+ if (vBodyLeng > vLeavingLeng - 6)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 鍖呴暱搴︿笉鍖归厤: 澹版槑 {vBodyLeng + 6}, 瀹為檯 {vLeavingLeng}");
+ break;
+ }
+
+ vPackBytes = new byte[vBodyLeng];
+ Array.Copy(fixBytes, vReadIndex + 6, vPackBytes, 0, vBodyLeng);
+
+ vPackBytes = encoder.BaseXorSub(vPackBytes);
+ Array.Copy(vPackBytes, 0, vCmdBytes, 0, 2);
+ var cmd = (ushort)((ushort)(vCmdBytes[0] << 8) + vCmdBytes[1]);
+ bool isRegist = false;
+
+ if (PackageRegedit.Contain(cmd))
+ {
+ vNetpack = PackageRegedit.TransPack(socketType, cmd, vPackBytes);
+ if (vNetpack != null)
+ {
+ m_LastPackageTime = DateTime.Now;
+ GameNetSystem.Instance.PushPackage(vNetpack, socketType);
+ isRegist = true;
+ }
+ }
+
+ vReadIndex += 6 + vBodyLeng;
+
+ if (!isRegist)
+ {
+#if UNITY_EDITOR
+ PackageRegedit.TransPack(socketType, cmd, vPackBytes);
+#endif
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 鏀跺寘寮傚父锛歿ex}");
+ }
+ }
+
+ private void OnWebSocketError(string error)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 閿欒: {error}");
+ }
+
+ private void OnWebSocketClose(WebSocketCloseCode code)
+ {
+ Debug.Log($"[ClientSocket-WebSocket] 杩炴帴鍏抽棴: {code}");
+ OnDisconnected?.Invoke();
+ }
+
+ public async void CloseConnect()
+ {
+ Debug.Log("[ClientSocket-WebSocket] ==== CloseConnect");
+
+ if (webSocket != null)
+ {
+ sendQueue.Clear();
+ await webSocket.Close();
+ webSocket = null;
+ }
+ }
+
+ private bool isSending = false;
+
+ private async void SendBytes(byte[] bytes)
+ {
+ // 璋冭瘯鏃ュ織锛氳緭鍑哄彂閫佺殑瀛楄妭鏁版嵁
+ // string hexString = "[WebSocket] SendBytes Length=" + bytes.Length + " Data=" + BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 32)).Replace("-", " ");
+ // if (bytes.Length > 32) hexString += "...";
+ // Debug.Log(hexString);
+
+ if (webSocket == null || webSocket.State != WebSocketState.Open)
+ {
+ Debug.LogError("[ClientSocket-WebSocket] 鏈繛鎺ワ紝鏃犳硶鍙戦��");
+ return;
+ }
+
+ // 闃熷垪鏈哄埗
+ lock (sendQueue)
+ {
+ if (isSending)
+ {
+ sendQueue.Enqueue(bytes);
+ return;
+ }
+ isSending = true;
+ }
+
+ try
+ {
+ await webSocket.Send(bytes);
+
+ // 澶勭悊闃熷垪涓殑涓嬩竴涓�
+ lock (sendQueue)
+ {
+ if (sendQueue.Count > 0)
+ {
+ byte[] nextBytes = sendQueue.Dequeue();
+ isSending = false;
+ SendBytes(nextBytes); // 閫掑綊鍙戦��
+ }
+ else
+ {
+ isSending = false;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 鍙戦�佸紓甯�: {ex.Message}");
+ lock (sendQueue)
+ {
+ isSending = false;
+ }
+ }
+ }
+
+ // WebGL闇�瑕佸湪Update涓疆璇㈡秷鎭�
+ public void DispatchMessageQueue()
+ {
+// #if !UNITY_EDITOR
+ webSocket?.DispatchMessageQueue();
+// #endif
+ }
+
+#endif
+
+ // ==================== 缁熶竴鐨勫叕鍏辨帴鍙o紙涓や釜骞冲彴閫氱敤锛�====================
+
+ /// <summary>
+ /// 鍙戦�佸崗璁寘
+ /// </summary>
+ public void SendInfo(GameNetPackBasic protocol)
+ {
+ if (!connected)
+ {
+ return;
+ }
+
+ if (protocol == null)
+ {
+ Debug.LogError("瑕佸彂鐨勪俊鎭璞′负绌�");
+ return;
+ }
+
+ if (protocol.combineBytes == null)
+ {
+ protocol.WriteToBytes();
+ }
+ protocol.CombineDatas(encoder);
+
+#if UNITY_EDITOR
+ NetPkgCtl.RecordPackage(socketType, protocol.vInfoCont, NetPackagetType.Client,
+ protocol.ToString(), FieldPrint.PrintFields(protocol), FieldPrint.PrintFieldsExpand(protocol, true));
+#endif
+
+ // 璋冭瘯鏃ュ織锛氭煡鐪� combineBytes 鐨勫唴瀹�
+ string hexString = "[SendInfo] Protocol=" + protocol.ToString() + " combineBytes.Length=" + protocol.combineBytes.Length +
+ " Data=" + BitConverter.ToString(protocol.combineBytes, 0, Math.Min(protocol.combineBytes.Length, 32)).Replace("-", " ");
+ if (protocol.combineBytes.Length > 32) hexString += "...";
+ Debug.Log(hexString);
+
+ sendBytesTotal += protocol.combineBytes.Length;
+ SendBytes(protocol.combineBytes);
+ }
+
+#if UNITY_EDITOR
+ /// <summary>
+ /// 鍙戦�佸師濮嬪瓧鑺傛暟鎹�
+ /// </summary>
+ public void SendInfo(byte[] vBytes)
+ {
+ if (!connected)
+ {
+ Debug.LogError("灏氭湭涓庤鍚庣閾炬帴锛佹棤娉曞彂閫佷俊鎭�");
+ return;
+ }
+
+ if (vBytes == null || vBytes.Length < 2)
+ {
+ Debug.LogError("瑕佸彂鐨勪俊鎭暟鎹负绌烘垨鏁版嵁涓嶈冻");
+ return;
+ }
+
+ // 鍔犲瘑骞剁粍瑁呭寘澶�
+ vBytes = encoder.BaseXorAdd(vBytes);
+ byte[] vFrameHead = new byte[] { 255, 204 };
+ byte[] vMsgBodyLength = BitConverter.GetBytes(vBytes.Length);
+ byte[] vTotal = new byte[vBytes.Length + 6];
+ Array.Copy(vFrameHead, 0, vTotal, 0, vFrameHead.Length);
+ Array.Copy(vMsgBodyLength, 0, vTotal, 2, vMsgBodyLength.Length);
+ Array.Copy(vBytes, 0, vTotal, 6, vBytes.Length);
+
+ SendBytes(vTotal);
+ }
+#endif
}
diff --git a/Main/Core/NetworkPackage/WebSocketNetworkService.cs b/Main/Core/NetworkPackage/WebSocketNetworkService.cs
deleted file mode 100644
index 44a7d7b..0000000
--- a/Main/Core/NetworkPackage/WebSocketNetworkService.cs
+++ /dev/null
@@ -1,466 +0,0 @@
-using Cysharp.Threading.Tasks;
-using NativeWebSocket;
-using System;
-using System.Collections.Generic;
-using System.Text;
-using UnityEngine;
-
-/// <summary>
-/// WebSocket 缃戠粶鏈嶅姟 - 鐢ㄤ簬灏忔父鎴忓钩鍙�
-/// </summary>
-public class WebSocketNetworkService : INetworkService
-{
- private WebSocket webSocket;
- private NetworkState _state = NetworkState.Disconnected;
- private string currentUrl;
-
- // 缁熻淇℃伅锛堜笌 ClientSocket 瀵归綈锛�
- private long getBytesTotal = 0; // 鎺ユ敹鐨勬暟鎹�婚噺
- private long sendBytesTotal = 0; // 鍙戦�佺殑鏁版嵁鎬婚噺
- private DateTime m_LastPackageTime = DateTime.MinValue;
-
- /// <summary>
- /// 鏈�鍚庢敹鍖呮椂闂达紙瀹炵幇鎺ュ彛锛�
- /// </summary>
- public DateTime LastPackageTime { get { return m_LastPackageTime; } }
-
- // 鍙戦�侀槦鍒楋紙涓� ClientSocket 瀵归綈锛�
- private Queue<byte[]> sendQueue = new Queue<byte[]>();
- private bool isSending = false;
-
- // 缂栬В鐮佸櫒锛堜笌 ClientSocket 瀵归綈锛�
- private GameNetEncode encoder = new GameNetEncode();
-
- // 鏈嶅姟鍣ㄧ被鍨嬶紙涓� ClientSocket 瀵归綈锛�
- private ServerType socketType = ServerType.Main;
-
- /// <summary>
- /// 鏋勯�犲嚱鏁帮紙涓� ClientSocket 瀵归綈锛�
- /// </summary>
- public WebSocketNetworkService(ServerType type)
- {
- this.socketType = type;
- }
-
- public NetworkState State
- {
- get => _state;
- private set
- {
- if (_state != value)
- {
- _state = value;
- OnStateChanged?.Invoke(value);
- }
- }
- }
-
- public bool IsConnected => State == NetworkState.Connected;
-
- public event Action<NetworkState> OnStateChanged;
-
- /// <summary>
- /// 杩炴帴鍒� WebSocket 鏈嶅姟鍣�
- /// </summary>
- public async UniTask<bool> ConnectAsync(string url)
- {
- if (IsConnected)
- {
- Debug.LogWarning($"[WebSocket] 宸茬粡杩炴帴鍒� {currentUrl}");
- return true;
- }
-
- try
- {
- State = NetworkState.Connecting;
- currentUrl = url;
-
- Debug.Log($"[WebSocket] 寮�濮嬭繛鎺�: {url}");
-
- // 鍒涘缓 WebSocket 杩炴帴锛堜笉浼� headers锛屼娇鐢ㄩ粯璁よ涓猴級
- webSocket = new WebSocket(url);
-
- // 娉ㄥ唽浜嬩欢鐩戝惉
- webSocket.OnOpen += OnWebSocketOpen;
- webSocket.OnMessage += OnWebSocketMessage;
- webSocket.OnError += OnWebSocketError;
- webSocket.OnClose += OnWebSocketClose;
-
- // 寮�濮嬭繛鎺�
- Debug.Log($"[WebSocket] 璋冪敤 Connect()...");
-
- // 鍚姩杩炴帴浠诲姟锛堜笉绛夊緟瀹冨畬鎴愶紝鍥犱负瀹冧細涓�鐩磋繍琛屽埌杩炴帴鍏抽棴锛�
- var connectTask = webSocket.Connect();
-
- // 绛夊緟 OnOpen 瑙﹀彂锛堟渶澶�5绉掞級
- var timeout = DateTime.Now.AddSeconds(5);
- while (State != NetworkState.Connected && DateTime.Now < timeout)
- {
- await UniTask.Yield();
- }
-
- Debug.Log($"[WebSocket] 绛夊緟缁撴潫锛屽綋鍓嶇姸鎬�: {State}, WebSocket.State: {webSocket.State}");
-
- if (IsConnected)
- {
- Debug.Log("[WebSocket] 鉁� 杩炴帴鎴愬姛");
- return true;
- }
- else
- {
- Debug.LogError($"[WebSocket] 鉁� 杩炴帴瓒呮椂鎴栧け璐ワ紝State={State}, WebSocket.State={webSocket?.State}");
- return false;
- }
- }
- catch (Exception ex)
- {
- Debug.LogError($"[WebSocket] 杩炴帴寮傚父: {ex.Message}\n{ex.StackTrace}");
- return false;
- }
- }
-
- /// <summary>
- /// 鏂紑杩炴帴锛堝紓姝ワ級
- /// </summary>
- public async UniTask DisconnectAsync()
- {
- Debug.LogWarning($"[WebSocket] DisconnectAsync 琚皟鐢�! State={State}");
- Debug.LogWarning($"[WebSocket] 璋冪敤鍫嗘爤:\n{System.Environment.StackTrace}");
-
- if (webSocket != null)
- {
- // 娓呯┖鍙戦�侀槦鍒�
- lock (sendQueue)
- {
- sendQueue.Clear();
- isSending = false;
- }
-
- await webSocket.Close();
- webSocket = null;
- }
- State = NetworkState.Disconnected;
- }
-
- /// <summary>
- /// 鏂紑杩炴帴锛堝悓姝ワ紝閫傞厤 ClientSocket.CloseConnect锛�
- /// </summary>
- public void Disconnect()
- {
- Debug.LogWarning($"[WebSocket] Disconnect 琚皟鐢�! State={State}");
- Debug.LogWarning($"[WebSocket] 璋冪敤鍫嗘爤:\n{System.Environment.StackTrace}");
- DisconnectAsync().Forget();
- }
-
- /// <summary>
- /// 鍙戦�佸崗璁寘锛堜笌 ClientSocket.SendInfo 瀹屽叏瀵归綈锛�
- /// </summary>
- public void SendInfo(GameNetPackBasic protocol)
- {
- if (!IsConnected)
- {
- Debug.LogError("[WebSocket] 鏈繛鎺ワ紝鏃犳硶鍙戦�佸崗璁寘");
- return;
- }
-
- if (protocol == null)
- {
- Debug.LogError("[WebSocket] 瑕佸彂鐨勪俊鎭璞′负绌�");
- return;
- }
-
- try
- {
- // 1. 鍑嗗鍗忚鏁版嵁
- if (protocol.combineBytes == null)
- {
- protocol.WriteToBytes();
- }
-
- // 2. 缁勫悎鏁版嵁锛堜笌 ClientSocket.SendInfo 涓�鑷达級
- protocol.CombineDatas(encoder);
-
-#if UNITY_EDITOR
- // 3. 璁板綍鍖呬俊鎭埌 NetPackageWindow锛堜笌 ClientSocket 瀵归綈锛�
- NetPkgCtl.RecordPackage(socketType, protocol.vInfoCont, NetPackagetType.Client,
- protocol.ToString(), FieldPrint.PrintFields(protocol), FieldPrint.PrintFieldsExpand(protocol, true));
-#endif
-
- byte[] data = protocol.dataBytes;
-
- // 4. 鍔犲瘑
- byte[] encryptedData = encoder.BaseXorAdd(data);
-
- // 5. 娣诲姞鍖呭ご锛�6瀛楄妭锛�0xFF 0xCC + 4瀛楄妭闀垮害灏忕搴忥紝涓� ClientSocket 涓�鑷达級
- int bodyLength = encryptedData.Length;
- byte[] sendData = new byte[bodyLength + 6];
- sendData[0] = 0xFF; // 涓� ClientSocket 涓�鑷�
- sendData[1] = 0xCC; // 涓� ClientSocket 涓�鑷�
- // 浣跨敤 BitConverter 灏忕搴忥紙涓� ClientSocket 涓�鑷达級
- byte[] lengthBytes = BitConverter.GetBytes(bodyLength);
- Array.Copy(lengthBytes, 0, sendData, 2, 4);
- Array.Copy(encryptedData, 0, sendData, 6, bodyLength);
-
- // 6. 鏇存柊缁熻锛堜笌 ClientSocket 瀵归綈锛�
- sendBytesTotal += sendData.Length;
-
- // 7. 鍙戦�侊紙寮傛锛�
- SendAsync(sendData).Forget();
- }
- catch (Exception ex)
- {
- Debug.LogError($"[WebSocket] 鍙戦�佸崗璁寘寮傚父: {ex.Message}\n{ex.StackTrace}");
- }
- }
-
- /// <summary>
- /// 鍙戦�佷簩杩涘埗鏁版嵁锛堝悓姝ラ噸杞斤紝閫傞厤 ClientSocket.SendInfo锛�
- /// </summary>
- public void SendInfo(byte[] data)
- {
- SendAsync(data).Forget();
- }
-
- /// <summary>
- /// 鍙戦�佷簩杩涘埗鏁版嵁锛堝甫闃熷垪鏈哄埗锛屼笌 ClientSocket 瀵归綈锛�
- /// </summary>
- public async UniTask SendAsync(byte[] data)
- {
- if (!IsConnected)
- {
- Debug.LogError("[WebSocket] 鏈繛鎺ワ紝鏃犳硶鍙戦�佹暟鎹�");
- return;
- }
-
- if (data == null || data.Length == 0)
- {
- Debug.LogError("[WebSocket] 鍙戦�佹暟鎹负绌�");
- return;
- }
-
- // 妫�鏌ユ秷鎭ぇ灏忥紙鏈�澶� 64KB锛�
- if (data.Length > 65536)
- {
- Debug.LogError($"[WebSocket] 娑堟伅杩囧ぇ: {data.Length} bytes锛堟渶澶� 64KB锛�");
- return;
- }
-
- // 闃熷垪鏈哄埗锛氬鏋滄鍦ㄥ彂閫侊紝鍔犲叆闃熷垪
- lock (sendQueue)
- {
- if (isSending)
- {
- sendQueue.Enqueue(data);
- Debug.Log($"[WebSocket] 鏁版嵁鍔犲叆鍙戦�侀槦鍒楋紝闃熷垪闀垮害: {sendQueue.Count}");
- return;
- }
- else
- {
- isSending = true;
- }
- }
-
- // 鍙戦�佹暟鎹�
- await SendBytesInternal(data);
- }
-
- /// <summary>
- /// 鍐呴儴鍙戦�佹柟娉曪紙澶勭悊闃熷垪锛�
- /// </summary>
- private async UniTask SendBytesInternal(byte[] data)
- {
- try
- {
- await webSocket.Send(data);
- sendBytesTotal += data.Length;
- Debug.Log($"[WebSocket] 鍙戦�佹垚鍔�: {data.Length} bytes锛屾�诲彂閫�: {sendBytesTotal} bytes");
-
- // 澶勭悊闃熷垪涓殑涓嬩竴涓秷鎭�
- byte[] nextData = null;
- lock (sendQueue)
- {
- if (sendQueue.Count > 0)
- {
- nextData = sendQueue.Dequeue();
- }
- else
- {
- isSending = false;
- }
- }
-
- if (nextData != null)
- {
- await SendBytesInternal(nextData);
- }
- }
- catch (Exception ex)
- {
- Debug.LogError($"[WebSocket] 鍙戦�佸け璐�: {ex.Message}");
-
- lock (sendQueue)
- {
- isSending = false;
- }
- }
- }
-
- /// <summary>
- /// WebSocket 杩炴帴鎴愬姛鍥炶皟
- /// </summary>
- private void OnWebSocketOpen()
- {
- Debug.Log($"[WebSocket] 鉁撯湏鉁� OnOpen 浜嬩欢瑙﹀彂 - 杩炴帴鎴愬姛: {currentUrl}");
- Debug.Log($"[WebSocket] WebSocket.State: {webSocket?.State}");
- State = NetworkState.Connected;
- Debug.Log($"[WebSocket] 褰撳墠鐘舵�佸凡鏇存柊涓�: {State}");
- }
-
- /// <summary>
- /// WebSocket 娑堟伅鎺ユ敹鍥炶皟锛堜笌 ClientSocket.ReadInfo 瀵归綈锛�
- /// </summary>
- private void OnWebSocketMessage(byte[] data)
- {
- // 瀹屾暣鐨勫寘澶勭悊娴佺▼锛堜笌 ClientSocket.ReadInfo 瀵归綈锛�
- try
- {
- if (data == null || data.Length < 6)
- {
- Debug.LogError($"[WebSocket] 鏀跺埌鏃犳晥鏁版嵁鍖�: {data?.Length ?? 0} bytes");
- return;
- }
-
- // 鏇存柊缁熻淇℃伅
- getBytesTotal += data.Length;
- Debug.Log($"[WebSocket] 鏀跺埌鍘熷娑堟伅: {data.Length} bytes");
-
- // 妫�鏌ュ寘澶达紙0xFF 0xCC锛屼笌 ClientSocket 涓�鑷达級
- if (data[0] != 0xFF || data[1] != 0xCC)
- {
- Debug.LogError($"[WebSocket] 鍖呭ご閿欒: 0x{data[0]:X2} 0x{data[1]:X2}锛屾湡鏈� 0xFF 0xCC");
- return;
- }
-
- // 璇诲彇鍖呬綋闀垮害锛堝皬绔簭锛屼笌 ClientSocket 涓�鑷达級
- int bodyLength = BitConverter.ToInt32(data, 2);
-
- if (data.Length < bodyLength + 6)
- {
- Debug.LogError($"[WebSocket] 鍖呴暱搴︿笉鍖归厤: 澹版槑 {bodyLength + 6}, 瀹為檯 {data.Length}");
- return;
- }
-
- // 鎻愬彇鍔犲瘑鐨勫寘浣擄紙璺宠繃6瀛楄妭鍖呭ご锛�
- byte[] encryptedBody = new byte[bodyLength];
- Array.Copy(data, 6, encryptedBody, 0, bodyLength);
-
- // 瑙e瘑鍖呬綋锛堜笌 ClientSocket.ReadInfo 涓�鑷达級
- byte[] decryptedData = encoder.BaseXorSub(encryptedBody);
-
- // 瑙f瀽 CMD锛堝墠2瀛楄妭锛�
- byte[] cmdBytes = new byte[2];
- Array.Copy(decryptedData, 0, cmdBytes, 0, 2);
- var cmd = (ushort)((ushort)(cmdBytes[0] << 8) + cmdBytes[1]);
-
- Debug.Log($"[WebSocket] 瑙e瘑鎴愬姛锛孋MD=0x{cmd:X4}");
-
- bool isRegist = false;
-
- // 杞崲鍗忚鍖咃紙涓� ClientSocket.ReadInfo 涓�鑷达級
- if (PackageRegedit.Contain(cmd))
- {
- GameNetPackBasic pack = PackageRegedit.TransPack(socketType, cmd, decryptedData);
- if (pack != null)
- {
- Debug.Log($"[WebSocket] 鏀跺埌鍗忚: {pack.GetType().Name}");
- m_LastPackageTime = DateTime.Now;
-
- // 鐩存帴鎺ㄩ�佸埌 GameNetSystem锛堜笌 ClientSocket 涓�鑷达級
- GameNetSystem.Instance.PushPackage(pack, socketType);
- isRegist = true;
- }
- }
-
- // 鏈敞鍐屽皝鍖呭鐞嗭紙涓� ClientSocket 涓�鑷达級
- if (!isRegist)
- {
-#if UNITY_EDITOR
- PackageRegedit.TransPack(socketType, cmd, decryptedData);
-#endif
- }
- }
- catch (Exception ex)
- {
- Debug.LogError($"[WebSocket] 娑堟伅澶勭悊寮傚父: {ex.Message}\n{ex.StackTrace}");
- }
- }
-
- /// <summary>
- /// WebSocket 閿欒鍥炶皟
- /// </summary>
- private void OnWebSocketError(string error)
- {
- Debug.LogError($"[WebSocket] 鉁� OnError 浜嬩欢瑙﹀彂: {error}");
- Debug.LogError($"[WebSocket] 褰撳墠鐘舵��: {State}, WebSocket.State: {webSocket?.State}");
- }
-
- /// <summary>
- /// WebSocket 鍏抽棴鍥炶皟锛堜笉鑷姩閲嶈繛锛屼笌 ClientSocket 涓�鑷达級
- /// </summary>
- private void OnWebSocketClose(WebSocketCloseCode code)
- {
- Debug.LogError($"[WebSocket] 鈯� OnClose 浜嬩欢瑙﹀彂!");
- Debug.LogError($"[WebSocket] 鍏抽棴浠g爜: {code} ({(int)code})");
- Debug.LogError($"[WebSocket] 涔嬪墠鐘舵��: {State}\n");
-
- // 鍒ゆ柇鏄皝鍏抽棴鐨�
- if (code == WebSocketCloseCode.Normal)
- {
- Debug.LogWarning("[WebSocket] 鈫� 姝e父鍏抽棴锛堝鎴风涓诲姩锛�");
- }
- else if (code == WebSocketCloseCode.Abnormal)
- {
- Debug.LogError("[WebSocket] 鈫� 寮傚父鍏抽棴锛堣繛鎺ヤ涪澶辨垨鏈嶅姟鍣ㄦ柇寮�锛�");
- }
- else
- {
- Debug.LogError($"[WebSocket] 鈫� 鍏朵粬鍘熷洜鍏抽棴: {code}");
- }
-
- State = NetworkState.Disconnected;
-
- // 娉ㄦ剰锛氫笉鑷姩閲嶈繛锛屼笌 ClientSocket 涓�鑷达紝鐢� GameNetSystem 鎺у埗閲嶈繛閫昏緫
- Debug.Log("[WebSocket] 杩炴帴宸叉柇寮�锛岀瓑寰� GameNetSystem 澶勭悊");
- }
-
- /// <summary>
- /// 鑾峰彇鎺ユ敹缁熻淇℃伅
- /// </summary>
- public long GetBytesTotal() => getBytesTotal;
-
- /// <summary>
- /// 鑾峰彇鍙戦�佺粺璁′俊鎭�
- /// </summary>
- public long GetSendBytesTotal() => sendBytesTotal;
-
- /// <summary>
- /// 鑾峰彇鍙戦�侀槦鍒楅暱搴�
- /// </summary>
- public int GetSendQueueCount()
- {
- lock (sendQueue)
- {
- return sendQueue.Count;
- }
- }
-
- /// <summary>
- /// 姣忓抚澶勭悊 WebSocket 娑堟伅锛堝繀椤诲湪 MonoBehaviour 鐨� Update 涓皟鐢級
- /// </summary>
- public void Update()
- {
-#if !UNITY_WEBGL || UNITY_EDITOR
- webSocket?.DispatchMessageQueue();
-#endif
- }
-}
diff --git a/Main/Core/NetworkPackage/WebSocketNetworkService.cs.meta b/Main/Core/NetworkPackage/WebSocketNetworkService.cs.meta
deleted file mode 100644
index dd41989..0000000
--- a/Main/Core/NetworkPackage/WebSocketNetworkService.cs.meta
+++ /dev/null
@@ -1,11 +0,0 @@
-fileFormatVersion: 2
-guid: 963e73ef1640ad24ca0948e6cb9d2198
-MonoImporter:
- externalObjects: {}
- serializedVersion: 2
- defaultReferences: []
- executionOrder: 0
- icon: {instanceID: 0}
- userData:
- assetBundleName:
- assetBundleVariant:
diff --git a/Main/Main.cs b/Main/Main.cs
index cf517e3..d14fce2 100644
--- a/Main/Main.cs
+++ b/Main/Main.cs
@@ -19,7 +19,7 @@
/// <summary>
/// 缃戠粶绫诲瀷閰嶇疆锛堝彲鍦ㄤ唬鐮佷腑淇敼鎴栭�氳繃 Inspector 閰嶇疆锛�
/// </summary>
- public static NetworkType CurrentNetworkType = NetworkType.TCP;
+ // public static NetworkType CurrentNetworkType = NetworkType.WebSocket;
public static List<IGameSystemManager> managers = new List<IGameSystemManager>();
--
Gitblit v1.8.0