From 51b0f6ed9f4e1d3bb6f8144470b46908c7699a96 Mon Sep 17 00:00:00 2001
From: yyl <yyl>
Date: 星期一, 11 五月 2026 16:20:37 +0800
Subject: [PATCH] Merge branch 'master' into h5version
---
Main/Core/NetworkPackage/Socket/ClientSocket.cs | 503 ++++++++++++++++++++++++++++++++++++++++++++++---------
1 files changed, 416 insertions(+), 87 deletions(-)
diff --git a/Main/Core/NetworkPackage/Socket/ClientSocket.cs b/Main/Core/NetworkPackage/Socket/ClientSocket.cs
index 6639be3..f2fa088 100644
--- a/Main/Core/NetworkPackage/Socket/ClientSocket.cs
+++ b/Main/Core/NetworkPackage/Socket/ClientSocket.cs
@@ -1,47 +1,88 @@
锘縰sing UnityEngine;
using System;
-using System.Collections;
using System.Collections.Generic;
+
+#if !UNITY_WEBGL
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
+ // 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; } }
+ private byte[] fragmentBytes; // TCP-to-WS缃戝叧鎸塗CP缂撳啿鍖烘媶鍖咃紝闇�瑕佽法娑堟伅閲嶇粍
+#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
+ 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];
+#if UNITY_WEBGL
+ string webSocketUrl;
+ bool webSocketOpened;
+#endif
public ClientSocket(ServerType type)
{
this.socketType = type;
}
+#if !UNITY_WEBGL
+ // ==================== TCP Socket 瀹炵幇 ====================
+
public void Connect(string _ip, int _port, Action<bool> _onConnected)
{
+ Debug.unityLogger.logEnabled = true;
try
{
ip = _ip;
port = _port;
onConnected = _onConnected;
+ Debug.Log($"[ClientSocket][Connect] 灏濊瘯杩炴帴: ip={_ip}, port={_port}");
//鐩墠娴嬭瘯鍒板紓姝ヤ袱涓棶棰�
// 1. BeginGetHostAddresses 涓嶆槑鎯呭喌涓嬩細寰堜箙鎵嶅洖璋冿紝瀵艰嚧瑙﹀彂瓒呮椂
// 2. 瓒呮椂鐨勬儏鍐典笅澶氭灏濊瘯鐧诲綍鍚庯紝浼氳Е鍙戝娆nGetHostAddresses锛屽鑷寸櫥褰曞紓甯�
@@ -57,29 +98,29 @@
ipAddress = ipAddresses[0];
#endif
-
+ Debug.Log($"[ClientSocket][Connect] 瑙f瀽鍒癷pAddress={ipAddress}, family={ipAddress.AddressFamily}");
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
- Debug.Log("褰撳墠浣跨敤鐨勭綉缁�: IPV6");
+ Debug.Log("[ClientSocket][Connect] 褰撳墠浣跨敤鐨勭綉缁�: IPV6");
m_Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
}
else
{
- Debug.Log("褰撳墠浣跨敤鐨勭綉缁�: IPV4");
+ Debug.Log("[ClientSocket][Connect] 褰撳墠浣跨敤鐨勭綉缁�: IPV4");
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
var ipEndPoint = new IPEndPoint(ipAddress, port);
if (ipEndPoint == null)
{
- Debug.Log("IpEndPoint is null");
+ Debug.LogError("[ClientSocket][Connect] IpEndPoint is null");
}
m_Socket.BeginConnect(ipEndPoint, new AsyncCallback(ConnectCallBack), null);
}
catch (Exception e)
{
- Debug.LogError(e.Message);
+ Debug.LogError($"[ClientSocket][Connect] 寮傚父: {e.Message}");
}
@@ -115,12 +156,14 @@
/// <param name="_result"></param>
private void ConnectCallBack(IAsyncResult _result)
{
+ Debug.unityLogger.logEnabled = true;
if (!_result.IsCompleted)
{
- Debug.Log("閾炬帴瓒呮椂锛�");
+ Debug.LogError("[ClientSocket][ConnectCallBack] 閾炬帴瓒呮椂锛�");
CloseConnect();
if (onConnected != null)
{
+ Debug.LogError("[ClientSocket][ConnectCallBack] onConnected(false) 瓒呮椂");
onConnected(false);
onConnected = null;
}
@@ -131,11 +174,12 @@
{
if (m_Socket != null && m_Socket.Connected)
{
- Debug.Log("纭鐨勯摼鎺ュ疄鐜�");
+ Debug.Log("[ClientSocket][ConnectCallBack] 纭鐨勯摼鎺ュ疄鐜�");
OnConnectSuccess();
}
else
{
+ Debug.LogError("[ClientSocket][ConnectCallBack] m_Socket涓簄ull鎴栨湭杩炴帴");
if (m_Socket != null)
{
m_Socket.Disconnect(true);
@@ -144,12 +188,13 @@
}
catch (System.Exception ex)
{
- Debug.Log(ex);
+ Debug.LogError($"[ClientSocket][ConnectCallBack] 寮傚父: {ex}");
}
finally
{
if (onConnected != null)
{
+ Debug.Log($"[ClientSocket][ConnectCallBack] onConnected({m_Socket != null && m_Socket.Connected})");
onConnected(m_Socket != null && m_Socket.Connected);
onConnected = null;
}
@@ -166,17 +211,21 @@
public void CloseConnect()
{
Debug.Log("==== CloseConnect");
+ Debug.unityLogger.logEnabled = true;
+ Debug.Log("[ClientSocket][CloseConnect] ==== CloseConnect");
try
{
isStopTreading = true;
if (m_packageThread != null)
{
m_packageThread.Abort();
+ m_packageThread = null;
}
}
catch (System.Exception ex)
{
Debug.Log(ex);
+ m_packageThread = null;
}
try
@@ -203,15 +252,19 @@
{
if (m_packageThread != null)
{
+ Debug.LogWarning("[ClientSocket][OnConnectSuccess] m_packageThread宸插瓨鍦紝鍏圓bort");
m_packageThread.Abort();
m_packageThread = null;
}
+ fragmentBytes = null; // 娓呴櫎涓婃杩炴帴娈嬬暀鐨勭鐗囩紦瀛�
m_LastPackageTime = DateTime.Now;
+ isStopTreading = false;
m_packageThread = new Thread(new ThreadStart(ReceiveInfo)); // 鍚姩绾跨▼鎺ユ敹淇℃伅
m_packageThread.IsBackground = true;
m_packageThread.Start();
- isStopTreading = false;
+ Debug.unityLogger.logEnabled = true;
+ Debug.Log("[ClientSocket][OnConnectSuccess] 杩炴帴鎴愬姛锛屽惎鍔ㄦ帴鏀剁嚎绋�");
}
/// <summary>
@@ -219,6 +272,8 @@
/// </summary>
private void ReceiveInfo()
{
+ Debug.unityLogger.logEnabled = true;
+ Debug.Log("[ClientSocket][ReceiveInfo] 鎺ユ敹绾跨▼鍚姩");
while (!isStopTreading)
{
try
@@ -226,14 +281,17 @@
var shutdown = false;
if (!m_Socket.Connected)
{
+ Debug.LogWarning("[ClientSocket][ReceiveInfo] m_Socket 宸叉柇寮�");
shutdown = true;
}
if (!shutdown)
{
var dataLength = m_Socket.Receive(bufferBytes);
+ Debug.Log($"[ClientSocket][ReceiveInfo] 鏀跺埌鏁版嵁闀垮害: {dataLength}");
if (dataLength <= 0)
{
+ Debug.LogWarning("[ClientSocket][ReceiveInfo] dataLength <= 0锛屽噯澶囨柇寮�");
shutdown = true;
}
else
@@ -247,6 +305,7 @@
if (shutdown)
{
+ Debug.LogWarning("[ClientSocket][ReceiveInfo] shutdown=true锛屽叧闂璖ocket");
isStopTreading = true;
m_Socket.Shutdown(SocketShutdown.Both);
m_Socket.Close();
@@ -254,13 +313,13 @@
}
catch (Exception e)
{
- Debug.Log(e);
+ Debug.LogError($"[ClientSocket][ReceiveInfo] 寮傚父: {e}");
}
}
+ Debug.Log("[ClientSocket][ReceiveInfo] 鎺ユ敹绾跨▼閫�鍑�");
}
- static byte[] vCmdBytes = new byte[2];
/// <summary>
/// 瑙f瀽鏁版嵁鍖咃細 FFCC+灏佸寘闀垮害+灏佸寘锛堝皝鍖呭ご+鏁版嵁锛夌粨鏋勪綋鍐呭
/// </summary>
@@ -274,6 +333,7 @@
if (fragmentBytes != null && fragmentBytes.Length > 0)
{
Array.Resize(ref fixBytes, vBytes.Length + fragmentBytes.Length);
+ Debug.Log($"[ClientSocket][ReadInfo] 瀛樺湪fragmentBytes, 闀垮害: {fragmentBytes.Length}");
Array.Copy(fragmentBytes, 0, fixBytes, 0, fragmentBytes.Length);
Array.Copy(vBytes, 0, fixBytes, fragmentBytes.Length, vBytes.Length);
}
@@ -295,9 +355,21 @@
Array.Copy(fixBytes, vReadIndex, fragmentBytes, 0, vLeavingLeng);
break;
}
+ // 鎵撳嵃鍖呭ご鍘熷瀛楄妭锛屼究浜庢帓鏌� OverflowException
+ byte h0 = fixBytes[vReadIndex], h1 = fixBytes[vReadIndex + 1],
+ h2 = fixBytes[vReadIndex + 2], h3 = fixBytes[vReadIndex + 3],
+ h4 = fixBytes[vReadIndex + 4], h5 = fixBytes[vReadIndex + 5];
vBodyLeng = BitConverter.ToInt32(fixBytes, vReadIndex + 2);
+ Debug.Log($"[ClientSocket][ReadInfo] vReadIndex={vReadIndex} vTotalLeng={vTotalLeng} vLeavingLeng={vLeavingLeng} header=[{h0:X2} {h1:X2} {h2:X2} {h3:X2} {h4:X2} {h5:X2}] vBodyLeng={vBodyLeng}");
+ if (vBodyLeng < 0)
+ {
+ Debug.LogError($"[ClientSocket][ReadInfo] vBodyLeng寮傚父({vBodyLeng})锛屼涪寮冨墿浣欐暟鎹紒fragmentBytes鎬婚暱={fixBytes.Length} vReadIndex={vReadIndex}");
+ fragmentBytes = null;
+ break;
+ }
if (vBodyLeng > vLeavingLeng - 6)// 鏈畬鏁寸殑鍖呭垯鐣欏寘
{
+ Debug.Log($"[ClientSocket][ReadInfo] 鍖呬笉瀹屾暣锛岀暀鍖�: vBodyLeng={vBodyLeng} vLeavingLeng={vLeavingLeng}");
fragmentBytes = new byte[vLeavingLeng];
Array.Copy(fixBytes, vReadIndex, fragmentBytes, 0, vLeavingLeng);
break;
@@ -317,10 +389,10 @@
vNetpack = PackageRegedit.TransPack(socketType, cmd, vPackBytes);
if (vNetpack != null)
{
- if (Launch.Instance.EnableNetLog)
- {
- Debug.LogFormat("鏀跺寘锛歿0}", vNetpack.GetType().Name);
- }
+ // if (Launch.Instance.EnableNetLog)
+ // {
+ // Debug.LogFormat("鏀跺寘锛歿0}", vNetpack.GetType().Name);
+ // }
m_LastPackageTime = DateTime.Now;
GameNetSystem.Instance.PushPackage(vNetpack, this.socketType);
isRegist = true;
@@ -346,71 +418,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 +463,318 @@
}
}
+ public void DispatchMessageQueue()
+ {
+ // TCP涓嶉渶瑕佽疆璇�
+ }
+
+#else
+ // ==================== WebSocket 瀹炵幇锛圵ebGL骞冲彴锛�====================
+
+ public async void Connect(string _ip, int _port, Action<bool> _onConnected)
+ {
+ Debug.unityLogger.logEnabled = true;
+ ip = _ip;
+ port = _port;
+ onConnected = _onConnected;
+
+ var scheme = Application.absoluteURL.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "wss" : "ws";
+ webSocketUrl = $"{scheme}://{_ip}:{_port}";
+ webSocketOpened = false;
+ Debug.Log($"[ClientSocket-WebSocket] 寮�濮嬭繛鎺�: {webSocketUrl}, pageUrl={Application.absoluteURL}");
+
+ try
+ {
+ webSocket = new WebSocket(webSocketUrl);
+
+ // 娉ㄥ唽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()
+ {
+ webSocketOpened = true;
+ Debug.Log($"[ClientSocket-WebSocket] 杩炴帴鎴愬姛: {webSocketUrl}");
+ m_LastPackageTime = DateTime.Now;
+
+ if (onConnected != null)
+ {
+ onConnected(true);
+ onConnected = null;
+ }
+ }
+
+ private void OnWebSocketMessage(byte[] data)
+ {
+ try
+ {
+ getBytesTotal += data.Length;
+
+ byte[] fixBytes = data;
+ // TCP-to-WS缃戝叧鎸塗CP缂撳啿鍖哄ぇ灏忔媶鍒嗭紝闇�璺ㄦ秷鎭噸缁勶紙涓嶵CP ReadInfo閫昏緫涓�鑷达級
+ if (fragmentBytes != null && fragmentBytes.Length > 0)
+ {
+ fixBytes = new byte[fragmentBytes.Length + data.Length];
+ Array.Copy(fragmentBytes, 0, fixBytes, 0, fragmentBytes.Length);
+ Array.Copy(data, 0, fixBytes, fragmentBytes.Length, data.Length);
+ }
+ fragmentBytes = null;
+
+ 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)
+ {
+ fragmentBytes = new byte[vLeavingLeng];
+ Array.Copy(fixBytes, vReadIndex, fragmentBytes, 0, vLeavingLeng);
+ break;
+ }
+
+ // 鏍¢獙FFCC鍖呭ご锛岄槻姝㈡暟鎹敊浣�
+ if (fixBytes[vReadIndex] != 0xFF || fixBytes[vReadIndex + 1] != 0xCC)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] FFCC鍖呭ご寮傚父: {fixBytes[vReadIndex]:X2} {fixBytes[vReadIndex + 1]:X2}, 涓㈠純鍓╀綑 {vLeavingLeng} 瀛楄妭");
+ fragmentBytes = null;
+ break;
+ }
+
+ vBodyLeng = BitConverter.ToInt32(fixBytes, vReadIndex + 2);
+ if (vBodyLeng <= 0)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 鍖呬綋闀垮害闈炴硶: {vBodyLeng}, 涓㈠純");
+ fragmentBytes = null;
+ break;
+ }
+ if (vBodyLeng > vLeavingLeng - 6)
+ {
+ fragmentBytes = new byte[vLeavingLeng];
+ Array.Copy(fixBytes, vReadIndex, fragmentBytes, 0, 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}");
+ if (!webSocketOpened && onConnected != null)
+ {
+ onConnected(false);
+ onConnected = null;
+ }
+ }
+
+ private void OnWebSocketClose(WebSocketCloseCode code)
+ {
+ Debug.LogError($"[ClientSocket-WebSocket] 杩炴帴鍏抽棴: code={code}, url={webSocketUrl}, opened={webSocketOpened}");
+ if (!webSocketOpened && onConnected != null)
+ {
+ onConnected(false);
+ onConnected = null;
+ }
+ OnDisconnected?.Invoke();
+ }
+
+ public async void CloseConnect()
+ {
+ Debug.Log("[ClientSocket-WebSocket] ==== CloseConnect\n" + System.Environment.StackTrace);
+ fragmentBytes = null;
+
+ 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
}
--
Gitblit v1.8.0