Пример #1
0
        /// <summary>
        /// Request time from NTP server and calls callback (if success)
        /// </summary>
        /// <param name="ntpServerAddress">NTP Server address</param>
        /// <param name="port">port</param>
        /// <param name="onRequestComplete">callback (called from other thread!)</param>
        public static void RequestTimeFromNTP(string ntpServerAddress, int port, Action <DateTime?> onRequestComplete)
        {
            NetSocket socket      = null;
            var       ntpEndPoint = MakeEndPoint(ntpServerAddress, port);

            NetManager.OnMessageReceived onReceive = (data, length, code, point) =>
            {
                if (!point.Equals(ntpEndPoint) || length < 48)
                {
                    return;
                }
                socket.Close();

                ulong intPart      = (ulong)data[40] << 24 | (ulong)data[41] << 16 | (ulong)data[42] << 8 | (ulong)data[43];
                ulong fractPart    = (ulong)data[44] << 24 | (ulong)data[45] << 16 | (ulong)data[46] << 8 | (ulong)data[47];
                var   milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
                onRequestComplete(new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)milliseconds));
            };

            //Create and start socket
            socket = new NetSocket(onReceive);
            socket.Bind(IPAddress.Any, IPAddress.IPv6Any, 0, false);

            //Send request
            int errorCode = 0;
            var sendData  = new byte[48];

            sendData[0] = 0x1B;
            var sendCount = socket.SendTo(sendData, 0, sendData.Length, ntpEndPoint, ref errorCode);

            if (errorCode != 0 || sendCount != sendData.Length)
            {
                onRequestComplete(null);
            }
        }
Пример #2
0
 /// <summary>
 /// NetManager constructor
 /// </summary>
 /// <param name="listener">Network events listener</param>
 /// <param name="maxConnections">Maximum connections (incoming and outcoming)</param>
 public NetManager(INetEventListener listener, int maxConnections)
 {
     socket                  = new NetSocket(ReceiveLogic);
     netEventListener        = listener;
     netEventsQueue          = new Queue <NetEvent>();
     netEventsPool           = new Stack <NetEvent>();
     NetPacketPool           = new NetPacketPool();
     NatPunchModule          = new NatPunchModule(socket);
     Statistics              = new NetStatistics();
     peers                   = new NetPeerCollection();
     connectingPeers         = new HashSet <IPEndPoint>(new IPEndPointComparer());
     this.maxConnections     = maxConnections;
     _connectedPeerListCache = new List <NetPeer>();
 }
Пример #3
0
 internal NatPunchModule(NetSocket socket)
 {
     _socket        = socket;
     _requestEvents = new Queue <RequestEventData>();
     _successEvents = new Queue <SuccessEventData>();
 }