using AxibugProtobuf; using Google.Protobuf; using HaoYueNet.ClientNetwork; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClientCore.Network { /// /// 继承网络库,以支持网络功能 /// public class NetworkHelper : NetworkHelperCore { public NetworkHelper() { //指定接收服务器数据事件 OnReceiveData += GetDataCallBack; //断开连接 OnClose += OnConnectClose; OnConnected += NetworkConnected; //网络库调试信息输出事件,用于打印网络内容 OnLogOut += NetworkDeBugLog; } public delegate void OnReConnectedHandler(); /// /// 重连成功事件 /// public event OnReConnectedHandler OnReConnected; /// /// 是否自动重连 /// public bool bAutoReConnect = false; /// /// 重连尝试时间 /// const int ReConnectTryTime = 1000; public void NetworkConnected(bool IsConnect) { NetworkDeBugLog($"NetworkConnected:{IsConnect}"); if (IsConnect) { } else { //连接失败 NetworkDeBugLog("连接失败!"); //自动重连开关 if (bAutoReConnect) ReConnect(); } } public void NetworkDeBugLog(string str) { //用于Unity内的输出 //Debug.Log("NetCoreDebug >> "+str); Console.WriteLine("NetCoreDebug >> " + str); } /// /// 接受包回调 /// /// 协议ID /// 错误编号 /// 业务数据 public void GetDataCallBack(int CMDID, int ERRCODE, byte[] data) { NetworkDeBugLog("收到消息 CMDID =>" + CMDID + " ERRCODE =>" + ERRCODE + " 数据长度=>" + data.Length); try { //抛出网络数据 NetMsg.Instance.PostNetMsgEvent(CMDID, data); } catch (Exception ex) { NetworkDeBugLog("逻辑处理错误:" + ex.ToString()); } } /// /// 关闭连接 /// public void OnConnectClose() { NetworkDeBugLog("OnConnectClose"); //自动重连开关 if (bAutoReConnect) ReConnect(); } bool bInReConnecting = false; /// /// 自动重连 /// void ReConnect() { if (bInReConnecting) return; bInReConnecting = true; bool bflagDone = false; do { //等待时间 Thread.Sleep(ReConnectTryTime); App.log.Debug($"尝试自动重连{LastConnectIP}:{LastConnectPort}……"); //第一步 if (Init(LastConnectIP, LastConnectPort)) { App.log.Debug($"自动重连成功!"); bflagDone = true; App.log.Debug($"触发重连后的自动逻辑!"); OnReConnected?.Invoke(); } } while (!bflagDone); bInReConnecting = false; } } }