| | |
| | | // WebSocket 实现(WebGL平台) |
| | | WebSocket webSocket; |
| | | public WebSocket socket { get { return webSocket; } } |
| | | private byte[] fragmentBytes; // TCP-to-WS网关按TCP缓冲区拆包,需要跨消息重组 |
| | | #endif |
| | | |
| | | public Action OnDisconnected; |
| | |
| | | { |
| | | getBytesTotal += data.Length; |
| | | |
| | | // WebSocket是消息模式,每次收到完整包,直接处理 |
| | | byte[] fixBytes = data; |
| | | // TCP-to-WS网关按TCP缓冲区大小拆分,需跨消息重组(与TCP 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; |
| | |
| | | vLeavingLeng = vTotalLeng - vReadIndex; |
| | | if (vLeavingLeng < 6) |
| | | { |
| | | Debug.LogError($"[ClientSocket-WebSocket] 包数据不足: {vLeavingLeng} bytes"); |
| | | 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) |
| | | { |
| | | Debug.LogError($"[ClientSocket-WebSocket] 包长度不匹配: 声明 {vBodyLeng + 6}, 实际 {vLeavingLeng}"); |
| | | fragmentBytes = new byte[vLeavingLeng]; |
| | | Array.Copy(fixBytes, vReadIndex, fragmentBytes, 0, vLeavingLeng); |
| | | break; |
| | | } |
| | | |
| | |
| | | public async void CloseConnect() |
| | | { |
| | | Debug.Log("[ClientSocket-WebSocket] ==== CloseConnect"); |
| | | fragmentBytes = null; |
| | | |
| | | if (webSocket != null) |
| | | { |