Пример #1
0
        public static async System.Threading.Tasks.Task <byte[]> Send(string host, int port, byte[] request)
        {
            var listenPort = 56800;
            var receiver   = new UdpSocketReceiver();

            TaskCompletionSource <byte[]> responseReceived = new TaskCompletionSource <byte[]>();

            receiver.MessageReceived += (sender, args) =>
            {
                responseReceived.SetResult(args.ByteData);
                receiver.StopListeningAsync();
            };

            //var client = new UdpSocketClient();

            await receiver.StartListeningAsync(listenPort);

            await receiver.SendToAsync(request, host, port);

            // listen for udp traffic on listenPort
            await responseReceived.Task;



            return(responseReceived.Task.Result);
        }
Пример #2
0
        // Connect to the time server and update system time
        private async Task StartAsync()
        {
            if (isBusy == false)
            {
                isBusy = true;

                Debug.WriteLine($"Syncing Timer with SNTP {TimeServer}");
                // Initialize data structure
                Initialize();

                var tcs = new TaskCompletionSource <byte[]>();
                using (var socket = new UdpSocketReceiver())
                {
                    socket.MessageReceived += async(sender, args) =>
                    {
                        await socket.StopListeningAsync();

                        tcs.SetResult(args.ByteData);
                    };

                    await socket.StartListeningAsync();

                    await socket.SendToAsync(SNTPData, TimeServer, 123);

                    SNTPData = await tcs.Task;
                }

                DestinationTimestamp = DateTime.Now;

                SetTime();

                isBusy = false;
            }
        }
        protected override async void OnAppearing()
        {
            Debug.WriteLine("OnAppearing: PacketsPage.xaml.cs");

            // In a multi-page app, everytime we come back to this page, OnAppearing
            // method is called, but we want to load the data only the first time
            // this page is loaded. In other words, when we go to ContactDetailPage
            // and come back, we don't want to reload the data. The data is already
            // there. We can control this using a switch: isDataLoaded.
            if (_isDataLoaded)
            {
                return;
            }

            _isDataLoaded = true;

            // I've extracted the logic for loading data into LoadData method.
            // Now the code in OnAppearing method looks a lot cleaner. The
            // purpose is very explicit. If data is loaded, return, otherwise,
            // load data. Details of loading the data is delegated to LoadData
            // method.
            await LoadData();

            base.OnAppearing();

            //app needs to turn off tcp server.
            MessagingCenter.Subscribe <App>(this, Events.APP_RESUME, async app => {
                //Do something
                Debug.WriteLine("APP_RESUME: PacketsPage.xaml.cs");
                await tcpServer.StartListeningAsync(tcpPort);
                await udpServer.StartListeningAsync(udpPort);
            });

            MessagingCenter.Subscribe <App>(this, Events.APP_SLEEP, app => {
                //Do something
                Debug.WriteLine("APP_SLEEP: PacketsPage.xaml.cs");
                tcpServer.StopListeningAsync();
                udpServer.StopListeningAsync();
            });

            MessagingCenter.Subscribe <App>(this, Events.APP_DISAPPEAR, app => {
                //Do something
                Debug.WriteLine("APP_DISAPPEAR: PacketsPage.xaml.cs");
                tcpServer.StopListeningAsync();
                udpServer.StopListeningAsync();
            });
        }
Пример #4
0
        public static async Task <DateTime> GetNetworkTimeAsync()
        {
            Debug.WriteLine("Entro in GetNTP " + DateTime.Now);
            //default Windows time server
            const string ntpServer = "time.windows.com";
            //const string ntpServer = "pool.ntp.org";
            //const string ntpServer = "time.nist.gov";

            // NTP message size - 16 bytes of the digest (RFC 2030)
            var ntpData = new byte[48];

            //Setting the Leap Indicator, Version Number and Mode values
            ntpData[0] = 0x1B;             //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

            var tcs = new TaskCompletionSource <byte[]>();

            using (var socket = new UdpSocketReceiver())
            {
                socket.MessageReceived += async(sender, args) =>
                {
                    await socket.StopListeningAsync();

                    tcs.SetResult(args.ByteData);
                };

                Debug.WriteLine("StartListening " + DateTime.Now);

                await socket.StartListeningAsync();                 // any free port >1000 will do

                Debug.WriteLine("SendTo " + DateTime.Now);
                await socket.SendToAsync(ntpData, ntpServer, 123).ContinueWith(_ => Task.FromResult(true)).TimeoutAfter(TimeSpan.FromSeconds(3));                 //.TimeoutAfter(TimeSpan.FromSeconds(3));

                Debug.WriteLine("SendTo conclusa");

                ntpData = await tcs.Task.TimeoutAfter(TimeSpan.FromSeconds(3));
            }

            //Offset to get to the "Transmit Timestamp" field (time at which the reply
            //departed the server for the client, in 64-bit timestamp format."
            const byte serverReplyTime = 40;

            //Get the seconds part
            ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

            //Get the seconds fraction
            ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

            //Convert From big-endian to little-endian
            intPart   = SwapEndianness(intPart);
            fractPart = SwapEndianness(fractPart);

            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

            //**UTC** time
            var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

            Debug.WriteLine("Esco da GetNTP " + DateTime.Now + " - " + networkDateTime + " - LOCALTIME: " + networkDateTime.ToLocalTime() + " - UTC: " + networkDateTime.ToUniversalTime());
            return(networkDateTime.ToLocalTime());
        }
Пример #5
0
 private static void StopDiscovery()
 {
     if (null != transmitSocket)
     {
         transmitSocket.DisconnectAsync();
     }
     if (null != receiveSocket)
     {
         receiveSocket.StopListeningAsync();
     }
 }
Пример #6
0
        private async Task CancelBroadcast()
        {
            if (!isBroadcasting)
            {
                return;
            }

            RefreshDevices.IsEnabled = false;
            RefreshDevices.Text      = "Refresh Devices";
            SendLog.Text            += "Stopping broadcast...\n";

            sendCancelSource.Cancel();
            await broadcaster.StopListeningAsync();

            isBroadcasting           = false;
            RefreshDevices.IsEnabled = true;
        }
 private void InitView()
 {
     Content = new StackLayout
     {
         Padding  = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0),
         Children =
         {
             new ListenerBindView(11011, this)
             {
                 StartListeningTapped = async i =>
                 {
                     await _receiver.StartListeningAsync(i, Global.DefaultCommsInterface);
                     return(true);
                 },
                 StopListeningTapped = async() =>
                 {
                     await _receiver.StopListeningAsync();
                 }
             },
             new MessagesView(_messagesObs, false)
         }
     };
 }
Пример #8
0
 public void Stop()
 {
     receiver.StopListeningAsync();
 }
Пример #9
0
        async public static Task <ServerList> BrowseForNoahServers(string friendlyName, string ipAddress)
        {
            var client   = new UdpSocketClient();
            var receiver = new UdpSocketReceiver();

            try
            {
                var address = GetIpAddressForBroadcast(ipAddress);
                //// convert our greeting message into a byte array
                string clientGUID        = "{B0BE0E7D-F70B-40BE-91AB-14125863B0B7}";
                System.Text.Encoding enc = System.Text.Encoding.UTF8;
                byte[] sendBuffer        = enc.GetBytes(clientGUID);

                receiver.MessageReceived += (sender, args) =>
                {
                    try
                    {
                        var from   = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort);
                        var fromIp = args.RemoteAddress;
                        var data   = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                        try
                        {
                            LocalRemoteHostInfo payload =
                                Helpers.Deserialize <LocalRemoteHostInfo>(Encoding.UTF8.GetString(args.ByteData, 0,
                                                                                                  args.ByteData.Length));
                            string guid = payload.LocalNoahServerGuid;
                            if (guid.Equals("{5FE140D5-1D3F-4E46-8892-15FA89DAE9F4}"))
                            {
                                bool duplicate = false;
                                foreach (ServerData servData in ServerCollection)
                                {
                                    if (servData.ServerIp.Equals(fromIp))
                                    {
                                        duplicate = true; //The adress is allready in the list
                                        break;
                                    }
                                }
                                if (duplicate == false) //No need to list Gatteway IP
                                {
                                    if (string.IsNullOrEmpty(friendlyName))
                                    {
                                        ServerCollection.Add(new ServerData
                                        {
                                            ServerName   = payload.HostName,
                                            FriendlyName = payload.FriendlyName,
                                            ServerIp     = payload.LocalHostIpAddress,
                                            RemoteHostId = payload.RemoteHostId
                                        });
                                    }
                                    else
                                    {
                                        if (friendlyName == payload.FriendlyName)
                                        {
                                            receiver.StopListeningAsync();
                                            ServerCollection.Add(new ServerData
                                            {
                                                ServerName   = payload.HostName,
                                                FriendlyName = payload.FriendlyName,
                                                ServerIp     = payload.LocalHostIpAddress,
                                                RemoteHostId = payload.RemoteHostId
                                            });

                                            //client.Dispose();
                                            //receiver.Dispose();
                                            waitTime = false;
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                    catch { }
                };
                try
                {
                    receiver.StartListeningAsync(listenPort);
                }
                catch (Exception e)
                {
                }
                client.ConnectAsync(address, port);
                client.SendAsync(sendBuffer);

                DateTime now  = DateTime.Now;
                DateTime stop = now + new TimeSpan(0, 0, 0, 5);


                while (waitTime)
                {
                    if (DateTime.Now > stop)
                    {
                        waitTime = false;
                    }
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Himsa.Noah.MobileAccessLayer.NoahServerUdpBrowser::BrowseForNoahServers(): {0}", e);
                throw;
            }
            finally
            {
                client.DisconnectAsync();
                receiver.StopListeningAsync();
                receiver.Dispose();
            }

            return(new ServerList
            {
                Servers = ServerCollection.ToArray()
            });
        }
Пример #10
0
        private void BroadcastReceived(object sender, UdpSocketMessageReceivedEventArgs args)
        {
            if (isReceiving)
            {
                Task.WaitAny(listener.StopListeningAsync());
                return;
            }

            if (args.RemoteAddress.Equals(address.ToString()))
            {
                return;
            }

            var           ClientRequest = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);
            SharingResult Result;

            try
            {
                Result = JsonConvert.DeserializeObject <SharingResult>(ClientRequest);
            }
            catch (Exception ex)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    ReceiveLog.Text += "Error when deserializing the response.\n";
                });
                return;
            }

            if (Result.Type == ValueType.RequestIP && Result.Value.Equals("GIMMEHYOURADDRESS"))
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    ReceiveLog.Text += $"Received broadcast from {args.RemoteAddress}\n";
                });

                var Response = JsonConvert.SerializeObject(new SharingResult()
                {
                    Name = DeviceInfo.Name, Type = ValueType.IPResponse, Value = address.ToString(), IsDiscoverable = isDiscoverable
                });
                var ResponseData = Encoding.UTF8.GetBytes(Response);
                if (Result.IsDiscoverable)
                {
                    IPAddress ip;
                    if (IPAddress.TryParse(args.RemoteAddress, out ip))
                    {
                        if (!discoveredDevices.Any(item => item.Address.ToString().Equals(ip.ToString())))
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                ReceiveLog.Text += $"Discovered device \"{Result.Name}\" ({ip.ToString()})\n";
                            });
                            discoveredDevices.Add(new DeviceDetails()
                            {
                                Name = Result.Name, Address = ip
                            });
                        }
                    }
                }
                Task.WaitAny(listener.SendToAsync(ResponseData, args.RemoteAddress, BROADCAST_PORT));
            }
        }