/// <summary> /// 注册消息回调事件 /// </summary> public static void Register(MessageType type, CallBack_client method) { if (!_callBacks.ContainsKey(type)) { _callBacks.Add(type, method); } else { Debug.LogWarning("注册了相同的回调事件"); } }
private static IEnumerator _Receive() { //持续接受消息 while (_curState == ClientState.Connected) { //解析数据包过程(服务器与客户端需要严格按照一定的协议制定数据包) byte[] data = new byte[4]; int length; //消息长度 MessageType type; //类型 int receive = 0; //接收长度 //异步读取 IAsyncResult async = _stream.BeginRead(data, 0, data.Length, null, null); while (!async.IsCompleted) { yield return(null); } //异常处理 try { receive = _stream.EndRead(async); } catch (Exception ex) { _curState = ClientState.None; Info.Instance.Print("消息包头接收失败:" + ex.Message, true); yield break; } if (receive < data.Length) { _curState = ClientState.None; Info.Instance.Print("消息包头接收失败", true); yield break; } using (MemoryStream stream = new MemoryStream(data)) { BinaryReader binary = new BinaryReader(stream, Encoding.UTF8); //UTF-8格式解析 try { length = binary.ReadUInt16(); type = (MessageType)binary.ReadUInt16(); } catch (Exception) { _curState = ClientState.None; Info.Instance.Print("消息包头接收失败", true); yield break; } } //如果有包体 if (length - 4 > 0) { data = new byte[length - 4]; //异步读取 async = _stream.BeginRead(data, 0, data.Length, null, null); while (!async.IsCompleted) { yield return(null); } //异常处理 try { receive = _stream.EndRead(async); } catch (Exception ex) { _curState = ClientState.None; Info.Instance.Print("消息包头接收失败:" + ex.Message, true); yield break; } if (receive < data.Length) { _curState = ClientState.None; Info.Instance.Print("消息包头接收失败", true); yield break; } } //没有包体 else { data = new byte[0]; receive = 0; } if (_callBacks.ContainsKey(type)) { //执行回调事件 CallBack_client method = _callBacks[type]; method(data); } else { Debug.Log("未注册该类型的回调事件"); } } }