public static bool RegistProtocol(Protocol protocol) { if (null == protocol) { return(false); } if (_registProtocolFactory.ContainsKey(protocol.GetMessageID())) { return(false); } _registProtocolFactory.Add(protocol.GetMessageID(), new ProtocolFactry(protocol.GetType())); return(true); }
public static void ReturnProtocolThreadSafe(Protocol protocol) { if (_registProtocolFactory != null && protocol != null) { lock (_registProtocolFactory) { ProtocolFactry factory = null; if (_registProtocolFactory.TryGetValue(protocol.GetMessageID(), out factory)) { factory.Return(protocol); } } } }
private void OnRecevie() { _recvQueue.Switch(); while (!_recvQueue.Empty()) { byte[] bytes = _recvQueue.Pop(); _protocolHead.Reset(); _protocolHead.Deserialize(bytes); _recvStream.Seek(0, SeekOrigin.Begin); _recvStream.SetLength(0); _recvStream.Write(bytes, ProtocolHead.Size, (int)_protocolHead.len + 4 - ProtocolHead.Size); _recvStream.Seek(0, SeekOrigin.Begin); Protocol.Protocol protocol = Protocol.Protocol.GetProtocolThreadSafe(_protocolHead.msgId); if (protocol == null) { #if DEBUG Debug.LogError("Ptc Not found: " + _protocolHead.msgId.ToString()); #endif continue; } try { #if DEBUG if (_protocolHead.len > 1024) { Debug.LogWarning("Recv Ptc:" + protocol.GetMessageID().ToString() + " to long:" + _protocolHead.len.ToString()); } #endif protocol.ThreadErrorCode = ProtocolErrorCode.NO_ERROR; protocol.DeSerialize(_recvStream); Protocol.Protocol.ReturnProtocolThreadSafe(protocol); } catch (Exception ex) { Debug.LogWarning("Ptc " + _protocolHead.msgId.ToString() + " deserialize fail: " + ex.Message.ToString()); protocol.ThreadErrorCode = ProtocolErrorCode.DESERIALIZE_ERROR; } if (protocol.ThreadErrorCode == ProtocolErrorCode.NO_ERROR) { try { protocol.Process(); } catch (Exception ex) { Debug.LogWarning("Ptc " + _protocolHead.msgId.ToString() + " Process fail: " + ex.Message.ToString()); protocol.ThreadErrorCode = ProtocolErrorCode.PROCESS_ERROR; } finally { Protocol.Protocol.ReturnProtocolThreadSafe(protocol); } } } }
public bool Send(Protocol.Protocol protocol) { _sendStream.SetLength(0); _sendStream.Position = 0; protocol.SerializeWithHead(_sendStream); #if DEBUG if (_sendStream.Length > 1024) { Debug.LogWarning("Send Ptc:" + protocol.GetMessageID() + " to long:" + _sendStream.Length); } #endif if (Send()) { return(true); } Debug.Log("send proto failed: " + protocol.ToString()); return(false); }