private async Task GetServerTimeOffsetAsync() { long min_diff = 1000000; long bestSentTime = 0, bestServerTime = 0, bestRecvTime = 0; for (int i = 0; i < Const.MAX_PING_TIMES; i++) { // send current time to server long sentTime = GetTimeMillis(); //byte[] jsonData = Encoding.ASCII.GetBytes("{\"sync_time\":" + sentTime + "}"); string jsonData = "{\"sync_time\":" + sentTime + "}"; _controlSocketWriter.WriteInt32(checked ((int)_controlSocketWriter.MeasureString(jsonData))); _controlSocketWriter.WriteString(jsonData); await _controlSocketWriter.StoreAsync(); // receive current time at server string recvMsg = await receiveMsgAsync(_controlSocketReader); JsonObject obj = JsonValue.Parse(recvMsg).GetObject(); long serverTime = (long)obj.GetNamedNumber("sync_time"); long recvTime = GetTimeMillis(); if (recvTime - sentTime < min_diff) { min_diff = recvTime - sentTime; bestSentTime = sentTime; bestServerTime = serverTime; bestRecvTime = recvTime; } } string sync_str = "" + bestSentTime + "\t" + bestServerTime + "\t" + bestRecvTime + "\n"; await _myLogger.WriteString(sync_str); Debug.WriteLine(sync_str); }
public async Task ProcessReceivedPacket(ReceivedPacketInfo receivedPacket) { Debug.WriteLine("Process Received Packet"); long recvFrameID = receivedPacket.frameID; string recvEngineID = receivedPacket.engineID; SentPacketInfo sentPacket = null; bool isSuccess; // increase appropriate amount of tokens int increaseCount = 0; for (long frameID = _prevRecvFrameID + 1; frameID < recvFrameID; frameID++) { sentPacket = null; if (Const.IS_EXPERIMENT) { // Do not remove since we need to measure latency even for the late response isSuccess = _sentPackets.TryGetValue(frameID, out sentPacket); } else { isSuccess = _sentPackets.TryRemove(frameID, out sentPacket); } if (isSuccess == true) { increaseCount++; } } Debug.WriteLine("Increasing Tokens by " + increaseCount); IncreaseTokens(increaseCount); // deal with the current response isSuccess = _sentPackets.TryGetValue(recvFrameID, out sentPacket); if (isSuccess == true) { // do not increase token if have already received duplicated ack if (recvFrameID > _prevRecvFrameID) { IncreaseTokens(1); } if (Const.IS_EXPERIMENT) { string log = recvFrameID + "\t" + recvEngineID + "\t" + sentPacket.generatedTime + "\t" + sentPacket.compressedTime + "\t" + receivedPacket.msgRecvTime + "\t" + receivedPacket.guidanceDoneTime + "\t" + receivedPacket.status; await _myLogger.WriteString(log + "\n"); } } if (recvFrameID > _prevRecvFrameID) { _prevRecvFrameID = recvFrameID; } }