public List <NetworkResponse> Read(int numPackets = 20) { List <NetworkResponse> responses = new List <NetworkResponse> (); while (theStream.DataAvailable && responses.Count < numPackets) { byte[] buffer = new byte[2]; theStream.Read(buffer, 0, 2); short bufferSize = BitConverter.ToInt16(buffer, 0); buffer = new byte[bufferSize]; //to allow for network latency, check number of bytes read and continue reading //until expected data is received int bytesRead = 0; int counter = 0; do { bytesRead += theStream.Read(buffer, bytesRead, bufferSize - bytesRead); counter++; } while(bytesRead < bufferSize); MemoryStream dataStream = new MemoryStream(buffer); short protocol_id = DataReader.ReadShort(dataStream); Type pType = NetworkProtocolTable.Get(protocol_id); if (counter > 1) { Debug.Log(string.Format( "Note, network latency issue identified, wait count = {0}, protocol ID = {1}", counter, protocol_id )); } //output packet-level info to screen for debugging purposes //DebugPacket (buffer, true, false); if (pType == null) { Debug.LogError("Invalid Response No. " + protocol_id + " [" + "Unknown" + "]"); } else { try { NetworkResponse args = pType.GetMethod("Parse").Invoke(null, new object[] { dataStream }) as NetworkResponse; if (args != null) { responses.Add(args); } } catch (Exception ex) { Debug.LogError("Failed Response No. " + protocol_id + " [" + pType.ToString() + "]"); Debug.LogException(ex); } } } return(responses); }
// Update is called once per frame void Update() { if (!cManager.Connected) { return; } while (requests.Count > 0) { NetworkRequest packet = requests.Peek(); if (cManager.Send(packet.GetBytes())) { requests.Dequeue(); if (packet.GetID() != 211) { Debug.Log("CW: Sent Request No. " + packet.GetID() + " [" + NetworkProtocolTable.Get(packet.GetID()).ToString() + "]"); } } } counter++; if (counter == interval) { //Debug.Log ("checking response buffer... (+50)"); counter = 0; } foreach (NetworkResponse args in cManager.Read()) { bool status = false; int protocol_id = args.GetID(); // One-Time if (callbackList.ContainsKey(protocol_id)) { if (callbackList [protocol_id].Count > 0) { callbackList [protocol_id].Dequeue() (args); status = true; } } // Listen if (listenList.ContainsKey(protocol_id)) { if (listenList [protocol_id].Count > 0) { foreach (Callback callback in listenList[protocol_id]) { callback(args); } status = true; } } if (args.GetID() != 211) { Debug.Log((status ? "Processed" : "Ignored") + " Response No. " + args.GetID() + " [" + NetworkProtocolTable.Get(args.GetID()).ToString() + "]"); } } }
void Awake() { NetworkProtocolTable.Init(); }