/// <summary> /// 注册网络异常事件 /// </summary> /// <param name="action"></param> public static void RegisterNetExEvent(Action action) { if (action != null) { ConnectionMgr.RegisterNetEx(action); } }
/// <summary> /// 获取一个逻辑消息,包括消息长度 /// </summary> /// <returns></returns> private Msg GetLogicMsg() { if (msgOffset < NetConfig.HEAD_LENGTH) { return(null); } //获取消息长度 byte[] lenBytes = new byte[4]; for (int i = 0; i < lenBytes.Length; i++) { lenBytes[i] = msgBuff[i]; } int len = BitConverter.ToInt32(lenBytes, 0); if (len == msgBuff.Count - 4) { byte[] logicMsg = new byte[4 + NetConfig.HEAD_LENGTH]; for (int i = 0; i < logicMsg.Length; i++) { logicMsg[i] = msgBuff[i]; } msgBuff.RemoveRange(0, logicMsg.Length); msgOffset -= logicMsg.Length; Msg msg = ConnectionMgr.DecodeMsgBuff(logicMsg); return(msg); } return(null); }
/// <summary> /// 异步建立网络连接 /// 不知道为啥原来的人加了其他东西,明天研究一下为啥 /// 已经搞明白了,2020.3.24 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="callback"></param> public static void CreateConnectByAsync(string ip, int port, LuaCallback callback) { bool isOk = false; bool isComplate = false; ConnectionMgr.ConnentByAsync(ip, port, (cb) => { isOk = cb.IsCompleted && (cb.AsyncState as MySocket).IsConnect(); isComplate = true; }); Debug.Log("创建新物体"); GameObject gameObject = new GameObject(); gameObject.name = "昙花一现"; var myMonoBehaviour = gameObject.AddComponent <MyMonoBehaviour>(); myMonoBehaviour.UpdateAction = () => { if (isComplate) { callback(isOk); GameObject.Destroy(myMonoBehaviour); } }; #region 测试没不能用的,但不是没用,是不能用 //这里开一个线程吧,安全点 //线程调用不了"注册心跳函数",因为子线程不能访问Unity的主线程,艹 // Thread thread = new Thread(()=>{ // while (true) // { // if (isComplate) // { // callback(isOk); // break; // } // } // }); // thread.Start(); //这个如果不是立马连上服务器,客户端会有卡顿的情况,哎,头疼 // while (true) // { // if (isComplate) // { // callback((bool) isOk); // break; // } // } #endregion }
/// <summary> /// 同步建立网络连接 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> public static bool CreateConnectBySync(string ip, int port) { bool isOk = ConnectionMgr.ConnectBySync(ip, port); if (isOk) { Debug.Log("同步连接网络成功"); } else { Debug.LogError("同步连接网络失败"); } return(isOk); }
private void Update() { while (ConnectionMgr.GetMsgCount() > 0) { Msg m = ConnectionMgr.GetMsg(); if (NetHelper.ToLuaMsg != null && m != null) { NetHelper.ToLuaMsg(m); } else { Debug.LogError("没有找到Lua中的处理方法"); } } }
/// <summary> /// 修改发送消息格式 /// 修改为msgId + msgBody(pb) /// </summary> /// <param name="sessionId"></param> /// <param name="msgId"></param> /// <param name="msgMainType"></param> /// <param name="msgSunType"></param> public static void SendMessage(int msgId, byte[] pb = null) { byte[] msg = ConnectionMgr.EncodeMsg(msgId, pb); ConnectionMgr.SendMsg(msg); }
/// <summary> /// 关闭连接 /// </summary> public static void CloseConnect() { ConnectionMgr.CloseConnect(); }