From a29fffa93dc66ff45589f8fd1f8584f7bcb9fdad Mon Sep 17 00:00:00 2001
From: yyl <yyl>
Date: 星期四, 05 二月 2026 18:41:17 +0800
Subject: [PATCH] h5 tcp switch to websocket
---
Main/Core/NetworkPackage/GameNetSystem.cs | 359 ++++++++++++++++++++++++++++++-----------------------------
1 files changed, 183 insertions(+), 176 deletions(-)
diff --git a/Main/Core/NetworkPackage/GameNetSystem.cs b/Main/Core/NetworkPackage/GameNetSystem.cs
index 92a27d7..7bbd6e3 100644
--- a/Main/Core/NetworkPackage/GameNetSystem.cs
+++ b/Main/Core/NetworkPackage/GameNetSystem.cs
@@ -2,11 +2,25 @@
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>
{
- // NetUpdateBehaviour m_NetUpdateBehaviour;
+ //闄愬埗瀹㈡埛绔殑涓嬩竴涓寘鏄櫥褰曞寘C0101_tagCPlayerLogin锛屽鏋滀笉鏄櫥褰曞寘涓嶅厑璁稿彂閫�
+ bool waitLogin = false; //绛夊緟鍙戦�佺櫥褰曞寘锛屽鏋滄湁鍏朵粬鍖呯洿鎺ュ睆钄斤紝閬垮厤鏂嚎閲嶈繛鐨勬儏鍐靛彂浜嗘敾鍑诲寘涔嬬被鐨�
+ //绛夊緟鏈嶅姟绔�0403鐨勫寘鍚庢墠鑳藉彂鍏朵粬鐨勫姛鑳藉寘锛屽彧鏈塁0123_tagCClientPackVersion 鍜� C0101_tagCPlayerLogin 鍙互鍙戦��
+ bool waitLoginMap = false;
+
+ // 缃戠粶鏈嶅姟鎺ュ彛锛堢粺涓�鏀寔 TCP 鍜� WebSocket锛�
+ private INetworkService networkService;
+
+ NetUpdateBehaviour m_NetUpdateBehaviour;
NeverConnectState neverConnectState;
AccountLoginState accountLoginState;
// CreateOrSelectRoleState createOrSelectRoleState;
@@ -70,34 +84,38 @@
}
}
- private ClientSocket mainSocket;
- public bool mainSocketConnected { get { return mainSocket == null ? false : mainSocket.connected; } }
+ private ClientSocket mainSocket; // 淇濈暀鍏煎锛屼絾涓嶅啀鐩存帴浣跨敤
+
+ public bool mainSocketConnected
+ {
+ get { return networkService?.IsConnected ?? false; }
+ }
public float timeSinceMainSocketLastProtocol
{
- get { return mainSocket == null ? Time.time : (float)(DateTime.Now - mainSocket.lastPackageTime).TotalSeconds; }
+ get
+ {
+ if (networkService == null)
+ return Time.time;
+
+ var lastTime = networkService.LastPackageTime;
+ if (lastTime == DateTime.MinValue)
+ return Time.time; // 浠庢湭鏀跺寘
+
+ return (float)(DateTime.Now - lastTime).TotalSeconds;
+ }
}
- public bool crossServerConnected_Loigc { get; set; }
- private ClientSocket crossServerSocket;
- public bool crossServerSocketConnected { get { return crossServerConnected_Loigc && (crossServerSocket == null ? false : crossServerSocket.connected); } }
-
- public float timeSinceCrossServerSocketLastProtocol
- {
- get { return crossServerSocket == null ? Time.time : (float)(DateTime.Now - crossServerSocket.lastPackageTime).TotalSeconds; }
- }
Queue<GameNetPackBasic> mainProtocolQueue = new Queue<GameNetPackBasic>();
- Queue<GameNetPackBasic> crossSeverProtocolQueue = new Queue<GameNetPackBasic>();
- public CrossServerData crossServerData { get; private set; }
public GameNetSystem()
{
var gameObject = new GameObject("NetUpdateBehaviour");
GameObject.DontDestroyOnLoad(gameObject);
- // m_NetUpdateBehaviour = gameObject.AddComponent<NetUpdateBehaviour>();
- // m_NetUpdateBehaviour.RegisterUpdateCallBack(OnUpdate);
+ m_NetUpdateBehaviour = gameObject.AddComponent<NetUpdateBehaviour>();
+ m_NetUpdateBehaviour.RegisterUpdateCallBack(OnUpdate);
neverConnectState = gameObject.AddComponent<NeverConnectState>();
accountLoginState = gameObject.AddComponent<AccountLoginState>();
@@ -113,9 +131,9 @@
{
try
{
- if (mainSocketConnected)
+ if (networkService != null && networkService.IsConnected)
{
- mainSocket.CloseConnect();
+ networkService.Disconnect();
}
}
catch (System.Exception ex)
@@ -123,79 +141,169 @@
Debug.Log(ex);
}
- mainSocket = new ClientSocket(ServerType.Main);
mainProtocolQueue.Clear();
- mainSocket.Connect(ip, port, (bool ok) =>
+ // 鏍规嵁 Main.CurrentNetworkType 閫夋嫨缃戠粶绫诲瀷
+ Debug.Log($"[GameNetSystem] 杩炴帴鏈嶅姟鍣� {ip}:{port}锛屼娇鐢▄(Main.CurrentNetworkType == NetworkType.WebSocket ? "WebSocket" : "TCP")}");
+
+ if (Main.CurrentNetworkType == NetworkType.WebSocket)
{
- if (onConnected != null)
- {
- onConnected(ok);
- }
- });
+ // 浣跨敤 WebSocket
+ ConnectWithWebSocket(ip, port, onConnected);
+ }
+ else
+ {
+ // 浣跨敤 TCP Socket锛堥�氳繃閫傞厤鍣級
+ ConnectWithTCP(ip, port, onConnected);
+ }
}
- public void BeginConnectCrossServer(string ip, int port, Action<bool> onConnected)
+ private async void ConnectWithTCP(string ip, int port, Action<bool> onConnected)
{
try
{
- crossServerConnected_Loigc = false;
- if (crossServerSocketConnected)
+ // 鍒涘缓 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)
{
- crossServerSocket.CloseConnect();
+ onConnected(success);
}
}
catch (System.Exception ex)
{
- Debug.Log(ex);
- }
-
- crossServerSocket = new ClientSocket(ServerType.CrossSever);
- crossSeverProtocolQueue.Clear();
- this.crossServerSocket.Connect(ip, port, (bool ok) =>
- {
+ Debug.LogError($"[GameNetSystem] TCP 杩炴帴寮傚父: {ex.Message}");
if (onConnected != null)
{
- onConnected(ok);
+ onConnected(false);
}
- });
+ }
}
- public void UpdateCrossServerData(string ip, int port, byte state)
+ private async void ConnectWithWebSocket(string ip, int port, Action<bool> onConnected)
{
- this.crossServerData = new CrossServerData(ip, port, state);
- if (this.crossServerData.crossState == 0)
+ try
{
- crossServerConnected_Loigc = false;
+ // 鍒涘缓 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)
+ {
+ netState = NetState.DisConnected;
+ }
+ }
+
+ //闄愬埗瀹㈡埛绔殑涓嬩竴涓寘鏄櫥褰曞寘C0101_tagCPlayerLogin锛屽鏋滀笉鏄櫥褰曞寘涓嶅厑璁稿彂閫�
+ public void SetIsWaitLogin(bool _wait)
+ {
+ waitLogin = _wait;
+ }
+
+ //绛夊緟鏈嶅姟绔�0403鐨勫寘鍚庢墠鑳藉彂鍏朵粬鐨勫姛鑳藉寘锛屽彧鏈塁0123_tagCClientPackVersion 鍜� C0101_tagCPlayerLogin 鍙互鍙戦��
+ public void SetIsWaitLoginMap(bool _wait)
+ {
+ waitLoginMap = _wait;
+ }
+
+ public bool GetIsWaitLoginMap()
+ {
+ return waitLoginMap;
+ }
+
+ //0403鐧诲綍涔嬪墠鐨勫寘缂撳瓨
+ Queue<GameNetPackBasic> sendQueue = new Queue<GameNetPackBasic>();
+
+ public void SendCachePackage()
+ {
+ int cnt = sendQueue.Count;
+ while (sendQueue.Count > 0)
+ {
+ SendInfo(sendQueue.Dequeue());
+ }
+ Debug.Log($"閲嶇偣鎻愰啋锛�0403鐧诲綍鍚� 鍙戦�佺紦瀛樺寘鏁伴噺 {cnt} 涓�");
}
public void SendInfo(GameNetPackBasic protocol)
{
- if (mainSocket != null)
+ Debug.LogError("protocol to send: " + protocol.ToString());
+
+ if (waitLogin)
{
- mainSocket.SendInfo(protocol);
+ if (protocol is not C0101_tagCPlayerLogin)
+ {
+ Debug.LogWarning("绛夊緟鎵ц鐧诲綍锛屼笉鍏佽鍙戦�佸叾浠栧寘 " + protocol.ToString());
+ return;
+ }
+ }
+
+ // 0102鏄粠鍦板浘鍙戦�佺殑 璇存槑宸茬櫥褰曪紝浣嗗彲鑳藉崱椤垮鑷撮�氱煡route鐘舵�佹參浜庡鎴风锛屼緷鐒堕渶瑕侀槻鑼�
+ if (waitLoginMap)
+ {
+ if (protocol is not C0123_tagCClientPackVersion && protocol is not C0101_tagCPlayerLogin)
+ {
+ Debug.LogError("閲嶇偣鎻愰啋锛氱櫥褰曞畬鎴愬墠鐨勫皝鍖呭厛鍔犲叆闃熷垪 绛�0403鍥炲寘鍚庡啀涓�璧峰彂閫佹湇鍔$ " + protocol.ToString());
+ sendQueue.Enqueue(protocol);
+ return;
+ }
+ }
+
+ if (networkService != null)
+ {
+ networkService.SendInfo(protocol);
DebugPkgCache.Push(protocol);
}
}
public void SendInfo(byte[] vBytes)
{
- if (mainSocket != null)
+ if (networkService != null)
{
- mainSocket.SendInfo(vBytes);
+ networkService.SendInfo(vBytes);
}
}
- public void SendToCrossServer(GameNetPackBasic protocol)
- {
- if (crossServerSocket != null)
- {
- protocol.socketType = ServerType.CrossSever;
- crossServerSocket.SendInfo(protocol);
- DebugPkgCache.Push(protocol);
- }
- }
public void PushPackage(GameNetPackBasic protocol, ServerType type)
{
@@ -208,17 +316,7 @@
if (PackageRegedit.Contain(protocol.cmd))
{
- switch (type)
- {
- case ServerType.Main:
- mainProtocolQueue.Enqueue(protocol);
- break;
- case ServerType.CrossSever:
- crossSeverProtocolQueue.Enqueue(protocol);
- break;
- default:
- break;
- }
+ mainProtocolQueue.Enqueue(protocol);
DebugPkgCache.Push(protocol);
}
@@ -233,18 +331,12 @@
{
try
{
- if (mainSocket != null)
+ if (networkService != null)
{
- mainSocket.CloseConnect();
- }
-
- if (crossServerSocket != null)
- {
- crossServerSocket.CloseConnect();
+ networkService.Disconnect();
}
mainProtocolQueue.Clear();
- crossSeverProtocolQueue.Clear();
}
catch (Exception ex)
{
@@ -253,49 +345,22 @@
finally
{
netState = NetState.DisConnected;
- // var loginModel = ModelCenter.Instance.GetModel<LoginModel>();
- // loginModel.busy = false;
- // CrossServerLogin.Instance.busy = false;
+ LoginManager.Instance.busy = false;
}
}
- public void DisconnectCrossServer()
- {
- try
- {
- if (crossServerSocket != null)
- {
- crossServerSocket.CloseConnect();
- }
- crossSeverProtocolQueue.Clear();
- }
- catch (Exception ex)
- {
- Debug.Log(ex);
- }
- finally
- {
- // CrossServerLogin.Instance.busy = false;
- }
- }
public void Reconnect()
{
try
{
- if (mainSocket != null)
+ if (networkService != null)
{
- mainSocket.CloseConnect();
- }
-
- if (crossServerSocket != null)
- {
- crossServerSocket.CloseConnect();
+ networkService.Disconnect();
}
mainProtocolQueue.Clear();
- crossSeverProtocolQueue.Clear();
}
catch (Exception ex)
{
@@ -304,36 +369,23 @@
finally
{
netState = NetState.AccountLogin;
- // CrossServerLogin.Instance.busy = false;
- // var loginModel = ModelCenter.Instance.GetModel<LoginModel>();
- // loginModel.busy = false;
- // loginModel.ReAccountLogin();
+ LoginManager.Instance.busy = false;
+ LoginManager.Instance.ReAccountLogin();
}
}
public void LoginOut()
{
- // if (CameraController.Instance != null)
- // CameraController.Instance.SetInGame(false);
- // DTC0102_tagCDBPlayer.isAfterPlayerDataInitialize = false;
-
try
{
- // ynmbxxjUtil.Instance.RoleLoginOut();
- crossServerConnected_Loigc = false;
+ SDKUtils.Instance.RoleLoginOut();
- if (mainSocket != null)
+ if (networkService != null)
{
- mainSocket.CloseConnect();
- }
-
- if (crossServerSocket != null)
- {
- crossServerSocket.CloseConnect();
+ networkService.Disconnect();
}
mainProtocolQueue.Clear();
- crossSeverProtocolQueue.Clear();
}
catch (Exception ex)
{
@@ -342,34 +394,11 @@
finally
{
netState = NetState.NerverConnect;
- // TODO YYL
- // CrossServerLogin.Instance.busy = false;
- // //ArenaManager.isArenaClient = false;
- // var loginModel = ModelCenter.Instance.GetModel<LoginModel>();
- // loginModel.busy = false;
- // WindowJumpMgr.Instance.ClearJumpData();
+ LoginManager.Instance.busy = false;
- // StageLoad.Instance.PushSceneLoadCommand(new StageLoad.StageLoadCommand()
- // {
- // toMapId = 1,
- // toLineId = 0,
- // needEmpty = false,
- // needLoadResource = true,
- // serverType = ServerType.Main,
- // isClientLoadMap = true
- // });
- // //CameraManager.uiCamera.clearFlags = CameraClearFlags.SolidColor;
- // //GameObject obj = GameObject.Find("NormalCanvas");
- // //int count = obj.transform.childCount;
- // //for (int i = count - 1; i >= 0; --i)
- // //{
- // // //Debug.LogError(obj.transform.GetChild(i).name);
- // // GameObject.Destroy(obj.transform.GetChild(i).gameObject);
- // //}
- // //SceneManager.LoadScene("Empty");
+ StageManager.Instance.ReturnToLoginScene();
NetLinkWin.Hide();
- // DTC0403_tagPlayerLoginLoadOK.neverLoginOk = true;
}
}
@@ -385,19 +414,16 @@
void OnUpdate()
{
+ if (networkService != null)
+ {
+ if (networkService is WebSocketNetworkService wsService) { wsService.Update(); }
+ }
+
lock (this)
{
while (mainProtocolQueue.Count > 0)
{
var package = mainProtocolQueue.Dequeue();
- if (package != null)
- {
- PackageRegedit.Distribute(package);
- }
- }
- while (crossSeverProtocolQueue.Count > 0)
- {
- var package = crossSeverProtocolQueue.Dequeue();
if (package != null)
{
PackageRegedit.Distribute(package);
@@ -417,31 +443,12 @@
DisConnected = 6,
}
- public struct CrossServerData
- {
- public string ip;
- public int port;
- public CrossServerState crossState;
-
- public CrossServerData(string ip, int port, byte state)
- {
- this.ip = ip;
- this.port = port;
- this.crossState = (CrossServerState)state;
- }
- }
-
- public enum CrossServerState
- {
- No = 0,
- Yes = 1,
- Error = 2,
- }
}
public enum ServerType
{
Main = 1,
- CrossSever = 2,
+ B430 = 2,
+ MainFight = 3,
}
--
Gitblit v1.8.0