/// <summary> /// 缓存中有数据进行处理, 先解码长度, 再解码消息 /// </summary> private void OnReceive() { //解码消息存储对象 byte[] buff = null; //当粘包解码器存在的时候,进行粘包处理 if (null != lengthDecode) { buff = lengthDecode(ref recvCache); //消息未接收全 退出数据处理 等待下次消息到达 if (null == buff) { m_bIsReading = false; return; } } else { //不用处理粘包 //缓存区中没有数据 直接跳出数据处理 等待消息到达 if (recvCache.Count == 0) { m_bIsReading = false; return; } buff = recvCache.ToArray(); recvCache.Clear(); } //反序列化方法是否存在 此方法必须存在 if (null == messageDecode) { throw new Exception("Message decode process is null"); } //进行消息反序列化 NetPacket netPacket = messageDecode(buff); //广播处理消息 //先缓存起来,放在Update中处理,防止处理时间过长造成堵塞 recvPool.AddRecvPacket(netPacket); //尾递归 防止在消息存储过程中 有其他消息到达而没有经过处理 OnReceive(); }
private void OnSocketReceive() { while (true) { int count = 0; tempBuffer.Clear(); connectEvent.WaitOne(); try { //发热修改:socket.Available <= 0 || (count = socket.Receive(tempBuffer.BBuffer)) < 0 会导致receive不会block的情况 if ((count = m_socket.Receive(tempBuffer.BBuffer)) < 0) { //Disconnect(); continue; } tempBuffer.Count = count; buffer.Append(tempBuffer); while (buffer.CanReadInt32()) { var len = buffer.ReadInt32(); if (buffer.Available >= len) { var packet = new NetPacket(); packet.ReadBuffer(buffer, len); if (LaunchConfigManager.LogEnable("NetManager")) { //LogUtils.LogWarning($"Net read num = {packet.number} cmd = {packet.cmd} zip = {packet.zip} len = {len}"); } recvPool.AddRecvPacket(packet); buffer.TruncateRead(); } else { if (LaunchConfigManager.LogEnable("NetManager")) { // LogUtils.LogWarning($"Net read out of bound, do revert"); } buffer.RevertLastRead(); break; } } } catch (SocketException e) { LogUtils.LogError($"Socket error : {e.SocketErrorCode} {e.ToString()}"); Close(m_socket, true); closeEvent.Set(); connectEvent.Reset(); } catch (ThreadAbortException e) { //忽略Thread.Abort异常 Close(m_socket, true); closeEvent.Set(); connectEvent.Reset(); } catch (Exception e) { LogUtils.LogError("Socket error : ", e); Close(m_socket, true); closeEvent.Set(); connectEvent.Reset(); } //Thread.Sleep(100); } }