private void HandleUDPMessage(Guid fromGuid, IPEndPoint endpoint, MessageType messageType, byte[] data) { UDPSibling udps = null; foreach (UDPSibling udpsother in udpSiblings) { if (udpsother.guid == fromGuid) { udps = udpsother; break; } } if (udps == null) { Console.WriteLine("Received UDP message from unknown client"); return; } switch (messageType) { case MessageType.DISCOVER: HandleUDPDiscover(udps, endpoint, data); break; case MessageType.NTP_MESSAGE: HandleUDPNTP(udps, data); break; case MessageType.NTP_COMPLETE: HandleUDPNTPComplete(udps, data); break; } }
private void SendUDPNTP(UDPSibling udps) { using (MessageWriter mw = new MessageWriter()) { mw.Write <long>(DateTime.UtcNow.Ticks); SendUDPMessage(udps, MessageType.NTP_MESSAGE, mw.GetMessageBytes()); } }
private void SendUDPDiscover(UDPSibling udps, bool isResponse) { using (MessageWriter mw = new MessageWriter()) { mw.Write <bool>(isResponse); SendUDPMessage(udps, MessageType.DISCOVER, mw.GetMessageBytes()); } }
private void AddClient(IPEndPoint endpoint, Guid udpAddress) { UDPSibling udps = new UDPSibling(); udps.guid = udpAddress; udps.endpoint = endpoint; lock (udpSiblings) { udpSiblings.Add(udps); } }
private void HandleUDPNTPComplete(UDPSibling udps, byte[] data) { using (MessageReader mr = new MessageReader(data)) { long sendTime = mr.Read <long>(); long peerTime = mr.Read <long>(); long receiveTime = DateTime.UtcNow.Ticks; udps.rtt = receiveTime - sendTime; udps.clockDiff = (sendTime + (udps.rtt / 2)) - peerTime; } }
private void HandleUDPDiscover(UDPSibling udps, IPEndPoint endpoint, byte[] data) { udps.isConnected = true; udps.endpoint = endpoint; using (MessageReader mr = new MessageReader(data)) { bool isResponse = mr.Read <bool>(); if (!isResponse) { SendUDPDiscover(udps, true); } } }
private void HandleUDPNTP(UDPSibling udps, byte[] data) { using (MessageReader mr = new MessageReader(data)) { long sendTime = mr.Read <long>(); long peerTime = DateTime.UtcNow.Ticks; using (MessageWriter mw = new MessageWriter()) { mw.Write <long>(sendTime); mw.Write <long>(peerTime); SendUDPMessage(udps, MessageType.NTP_COMPLETE, mw.GetMessageBytes()); } } }
private void RemoveClient(Guid udpAddress) { UDPSibling udps = null; lock (udpSiblings) { foreach (UDPSibling udpsother in udpSiblings) { if (udpsother.guid == udpAddress) { udps = udpsother; break; } } udpSiblings.Remove(udps); } }
//This really isn't at all thought out, but I'm going to leave it now because. private void SendUDPMessage(UDPSibling udps, MessageType mt, byte[] data) { byte[] sendData = null; using (MessageWriter mw = new MessageWriter()) { mw.Write <byte[]>(udpAddress.ToByteArray()); mw.Write <int>((int)mt); if (data == null || data.Length == 0) { mw.Write <int>(0); } else { mw.Write <int>(data.Length); mw.Write <byte[]>(data); } sendData = mw.GetMessageBytes(); } udpClient.Send(sendData, sendData.Length, udps.endpoint); }