Beispiel #1
0
        private async Task StartListeningAsyncUDP(int portNum)
        {
            listenerUDP.MessageReceived += ListenerUDP_MessageReceived;
            await listenerUDP.StartListeningAsync(portNum);

            ListenUdpLoop();
        }
Beispiel #2
0
        private async Task SendBroadcast()
        {
            if (isSending || isBroadcasting)
            {
                return; // don't want to keep sending broadcast when sending files
            }
            isBroadcasting           = true;
            RefreshDevices.IsEnabled = false;

            sendCancelSource = new CancellationTokenSource();
            discoveredDevices.Clear();

            RefreshDevices.Text = "Stop Refresh";
            SendLog.Text       += "Now sending...\n";

            // convert our greeting message into a byte array
            var Response = JsonConvert.SerializeObject(new SharingResult()
            {
                Name = DeviceInfo.Name, Type = ValueType.RequestIP, Value = "GIMMEHYOURADDRESS", IsDiscoverable = isDiscoverable
            });
            var msgBytes = Encoding.UTF8.GetBytes(Response);

            // send to address:port,
            // no guarantee that anyone is there
            // or that the message is delivered.
            await broadcaster.StartListeningAsync(BROADCAST_PORT);

            RefreshDevices.IsEnabled = true;
            await PeriodicTask.RunAsync(broadcaster.SendToAsync(msgBytes, broadcast.ToString(), BROADCAST_PORT), TimeSpan.FromSeconds(2), sendCancelSource.Token);
        }
Beispiel #3
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;
            }
        }
Beispiel #4
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);
        }
        public async void Listen(int listenPort)
        {
            var receiver = new UdpSocketReceiver();

            receiver.MessageReceived += (sender, args) =>
            {
                // get the remote endpoint details and convert the received data into a string
                var from = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort);
                var data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                string messageReceived = string.Format("{0} - {1}", from, data);
                Console.WriteLine(messageReceived);

                InvokeMessageReceived(args.RemoteAddress, int.Parse(args.RemotePort), messageReceived);

                //receiver.SendToAsync(args.ByteData, args.RemoteAddress, 5001);
                //receiver.SendToAsync(args.ByteData, args.RemoteAddress, int.Parse(args.RemotePort));
                //receiver.SendToAsync(args.ByteData, args.RemoteAddress, 5002);
            };

            // listen for udp traffic on listenPort
            await receiver.StartListeningAsync(listenPort);

            Console.WriteLine("Listening on " + listenPort);
        }
Beispiel #6
0
        protected override async void OnHandleIntent(Intent intent)
        {
            //UDP Receiver
            var listenPort = 15000;
            var receiver   = new UdpSocketReceiver();

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

                //Falls Link übermittelt
                if (string.IsNullOrEmpty(data) == false)
                {
                    //Starte MainActivity (mit erhaltener URI)
                    Intent i = new Intent(this, typeof(MainActivity));
                    i.SetData(Uri.Parse(data));
                    //i.AddFlags(ActivityFlags.NewTask);
                    this.StartActivity(i);
                }
            };

            //Abhören am UDP Port starten
            await receiver.StartListeningAsync(listenPort);
        }
Beispiel #7
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());
        }
Beispiel #8
0
        public async Task ReceiveMessage()
        {
            try
            {
                receiver.MessageReceived += async(sender, args) =>
                {
                    // get the remote endpoint details and convert the received data into a string


                    var from = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort);
                    var data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                    Console.WriteLine("Received " + data);

                    if (data.IndexOf("Server received") > -1)
                    {
                        Console.WriteLine("Received echo " + data);
                        return;
                    }

                    string returnMsg = String.Format("Server received {0} - {1}", from, data);
                    var    msgBytes  = Encoding.UTF8.GetBytes(returnMsg);

                    await client.SendAsync(msgBytes);

                    Console.WriteLine("Sending: " + returnMsg);

                    EndPoint remoteEnd = new IPEndPoint(IPAddress.Parse(this.sendsTo), this.sendsOn);
                    _socket.SendTo(msgBytes, remoteEnd);
                    Console.WriteLine("Sent using clean socket: " + returnMsg);

                    await clientUnconnected.SendToAsync(msgBytes, this.sendsTo, int.Parse(args.RemotePort));

                    EndPoint remoteEndLocal = new IPEndPoint(IPAddress.Parse(this.sendsTo), int.Parse(args.RemotePort));
                    _socket.SendTo(msgBytes, remoteEndLocal);
                    Console.WriteLine("Sent using clean socket (local): " + returnMsg);

                    EndPoint remoteEndLocal2 = new IPEndPoint(IPAddress.Parse(args.RemoteAddress), int.Parse(args.RemotePort));
                    _socket.SendTo(msgBytes, remoteEndLocal2);
                    Console.WriteLine("Sent using clean socket (local): " + returnMsg);
                };

                Console.WriteLine("Listening on " + this.receivesOn);

                await receiver.StartListeningAsync(0);

                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                byte[] buffer          = new byte[1024];
                e.SetBuffer(buffer, 0, buffer.Length);

                e.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);

                _socket.ReceiveAsync(e);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #9
0
        private async Task StartListeningAsyncUDP(int portNum)
        {
            if (listenerUDP == null)
            {
                throw new InvalidOperationException("Cannot listen on UDP when in TCP only mode.");
            }

            listenerUDP.MessageReceived += ListenerUDP_MessageReceived;
            await listenerUDP.StartListeningAsync(portNum);

            ListenUdpLoop();
        }
Beispiel #10
0
        public static async void GetListOfLocalHosts(string ipAddr)
        {
            receiveSocket = new UdpSocketReceiver();
            await receiveSocket.StartListeningAsync(RxPort);



            await StartDiscovery(OnServerDiscovered, ipAddr);

            // Wait until the control thread is done before proceeding.
            // This keeps the inactivity timers from overlapping.
        }
 public async Task Init()
 {
     try
     {
         await receiver.StartListeningAsync(listenPort);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
         throw;
     }
 }
Beispiel #12
0
        private async Task ListenForBroadcast()
        {
            if (isReceiving)
            {
                return;
            }

            ReceiveLog.Text       += "Now listening...\n";
            Discoverable.IsEnabled = false;
            await listener.StartListeningAsync(BROADCAST_PORT);

            Discoverable.IsEnabled = true;
        }
        public async void StartUDPReceive()
        {
            await udpReceiver.StartListeningAsync(PORT);

            udpReceiver.MessageReceived += (sender, args) =>
            {
                string data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                List <string> info = data.Split('*').ToList();
                if (info[0] == "1")
                {
                    ReceivedDiscoverReply(IPAddress.Parse(args.RemoteAddress), info.Skip(1).ToList());
                }
            };
        }
Beispiel #14
0
        public static async void Start()
        {
            udpReciever.MessageReceived += async(sender, args) =>
            {
                parseUdpMessage(args.RemoteAddress, args.ByteData);
            };

            try
            {
                await udpReciever.StartListeningAsync(Global.UdpPort);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
        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();
            });
        }
Beispiel #16
0
        public async void Connect()
        {
            try
            {
                if (UdpClient != null)
                {
                    try
                    {
                        await UdpClient.StopListeningAsync();

                        UdpClient.Dispose();
                    }
                    catch (Exception ex)
                    {
                        if (IsDebug)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                }

                UdpClient = new UdpSocketReceiver();
                UdpClient.MessageReceived += OnMessageReceived;
            }
            catch (SocketException ex)
            {
                if (IsDebug)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return;
                }
            }

            await UdpClient.StartListeningAsync(LocalEndpoint.Port);

            try
            {
                ConnectRequest();
            }
            catch (Exception ex)
            {
                if (IsDebug)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
Beispiel #17
0
        public async Task StartAsync()
        {
            List <CommsInterface> interfaces = await CommsInterface.GetAllInterfacesAsync();

            this.receiver = new UdpSocketReceiver();

            receiver.MessageReceived += this.ReceiverOnMessageReceived;

            try {
                // listen for udp traffic on listenPort
                await receiver.StartListeningAsync(this.listenPort);

                this.log($"listening on port {this.listenPort}");
            }
            catch (Exception e) {
                this.log($"failed to listen on port {this.listenPort}.{Environment.NewLine}{e}");
            }
        }
Beispiel #18
0
        public async Task <byte[]> Receive(IPEndPoint remoteHost)
        {
            var receiver = new UdpSocketReceiver();

            byte[] data = new byte[1];

            receiver.MessageReceived += (sender, args) =>
            {
                // get the remote endpoint details and convert the received data into a string
                data = args.ByteData;
            };
            await receiver.StartListeningAsync(remoteHost.Port);

            System.Console.WriteLine(System.DateTime.Now.ToString() + "<<< " + remoteHost);
            System.Console.WriteLine(FormatterHelper.Deserialize(data).ToString());
            System.Console.WriteLine();
            return(data);
        }
Beispiel #19
0
        public Listener()
        {
            Console.WriteLine("Starting Server");
            var udpReceived = new UdpSocketReceiver();

            udpReceived.StartListeningAsync(8888);

            udpReceived.MessageReceived += (sender, args) =>
            {
                System.Console.WriteLine($"Remote adrres: {args.RemoteAddress}");
                System.Console.WriteLine($"Remote port: {args.RemotePort}");

                var str = System.Text.Encoding.UTF8.GetString(args.ByteData);
                System.Console.WriteLine($"Messsage: {str}");
                MainWindow._current.AddMessage(str, true);
                MainWindow._current.SentenceAnalyzer.Analyze(str);
            };
        }
Beispiel #20
0
        public async void StartUDPReceive()
        {
            await udpReceiver.StartListeningAsync(PORTR);

            udpReceiver.MessageReceived += (sender, args) =>
            {
                string data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                List <string> info = data.Split('*').ToList();

                switch (info[0])
                {
                case "0":
                    break;

                case "1":
                    ReceivedDiscoverReply(IPAddress.Parse(args.RemoteAddress), info /*.Skip(1).ToList()*/);
                    break;

                case "3":
                    ReceivedBindReply(IPAddress.Parse(args.RemoteAddress), info.Skip(1).ToList());
                    break;

                case "5":
                    ReceivedBindDroppedAcknowledge();
                    break;

                case "7":
                    break;

                case "9":
                    break;

                case "a":
                    KeepAliveReceived();
                    break;

                default:
                    ReceivedInvalidUDP(info);
                    break;
                }
                ;
            };
        }
Beispiel #21
0
        async protected override void OnStart()
        {
            var receiver = new UdpSocketReceiver();

            receiver.MessageReceived += (sender, args) =>
            {
                var data = System.Text.Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);
                if (data.StartsWith(MAPLE_HOSTNAME, System.StringComparison.CurrentCultureIgnoreCase))
                {
                    var address = data.Split(new char[] { '=' })[1];
                    if (string.Compare(address, DehydratorHostAddress) != 0)
                    {
                        DehydratorHostAddress = address;
                        Debug.WriteLine("HostAddress updated: " + DehydratorHostAddress);
                    }
                }
            };
            await receiver.StartListeningAsync(MAPLE_SERVER_BROADCAST_PORT);
        }
Beispiel #22
0
        private static async void UdpListener()
        {
            var udpReceived = new UdpSocketReceiver();
            await udpReceived.StartListeningAsync(1234, allowMultipleBindToSamePort : true);

            var udpMessageSubscriber = udpReceived.ObservableMessages.Subscribe(
                msg =>
            {
                System.Console.WriteLine($"Remote adrres: {msg.RemoteAddress}");
                System.Console.WriteLine($"Remote port: {msg.RemotePort}");

                var str = System.Text.Encoding.UTF8.GetString(msg.ByteData);
                System.Console.WriteLine($"Messsage: {str}");
            },
                ex =>
            {
                // Exceptions received here;
            });

            udpMessageSubscriber.Dispose();
        }
        private async Task Pair()
        {
            await Task.Delay(4000);

            ProgressText = $"Start pairing";
            OnPropertyChanged("ProgressText");
            // give some time to connect
            await Task.Delay(10000);

            var currentIp = wifiManager.GetCurrentIp();

            ProgressText = $"Current Ip address is {currentIp}";
            OnPropertyChanged("ProgressText");

            var msg      = $"IOTC:{currentIp}:5000";
            var msgBytes = Encoding.UTF8.GetBytes(msg);

            udpReceiver.MessageReceived += StartSendCredentials;
            await udpReceiver.StartListeningAsync(5000);

            int retry = 0;

            try
            {
                while (retry < 5)
                {
                    await udpClient.SendToAsync(msgBytes, address, port);

                    await Task.Delay(500);

                    retry++;
                }
            }
            catch (SocketException ex)
            {
                ProgressText = $"Error Sending pairing message {ex.Message}";
                OnPropertyChanged("ProgressText");
            }
        }
Beispiel #24
0
        public async Task WaitForCompanion()
        {
            Serializer = new ProtobufNetworkSerializer();
            var tcs = new TaskCompletionSource <bool>();

            listener = new UdpSocketReceiver();
            listener.MessageReceived += (s, e) =>
            {
                remoteAddress = e.RemoteAddress;
                remotePort    = e.RemotePort;

                var dto          = Serializer.Deserialize <BaseDto>(e.ByteData);
                var handshakeDto = dto as PingDto;
                if (handshakeDto != null)
                {
                    var msg = handshakeDto.Message;
                }
                tcs.TrySetResult(true);
            };
            await listener.StartListeningAsync(Port);

            await tcs.Task;
        }
 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)
         }
     };
 }
 private async void iniReceiver()
 {
     await _receiver.StartListeningAsync(_port);
 }
Beispiel #27
0
 public void Start(int port)
 {
     receiver.StartListeningAsync(port);
 }
Beispiel #28
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()
            });
        }
        public PacketsPage()
        {
            InitializeComponent();

            tcpPort = SettingsPage.TCPPort;
            udpPort = SettingsPage.UDPPort;

            tcpServer = new TcpSocketListener();
            udpServer = new UdpSocketReceiver();

            tcpServer.ConnectionReceived += TcpConnection;
            udpServer.MessageReceived    += UdpConnection;

            Task.Run(async() =>
            {
                await tcpServer.StartListeningAsync(tcpPort);
                await udpServer.StartListeningAsync(udpPort);
                SettingsPage.TCPPort = tcpServer.LocalPort;

                MessagingCenter.Send(this, Events.BOUND_PORTS_CHANGED, 0);
            });


            //udpServer.StartListeningAsync(udpPort);

            /*
             += async (sender, args) =>
             * {
             * var client = args.SocketClient;
             *
             * var bytesRead = -1;
             * var buf = new byte[1];
             *
             * while (bytesRead != 0)
             * {
             *  bytesRead = await args.SocketClient.ReadStream.ReadAsync(buf, 0, 1);
             *  //if (bytesRead > 0)
             *  //    Debug.Write(buf[0]);
             * }
             * };
             */

            _connection = DependencyService.Get <ISQLiteDb>().GetConnection();

            /*
             *          var demopackets = Packet.GetDemoPackets();
             * for (int i = 0; i < demopackets.Count(); i++) {
             *  _thepackets.Add(demopackets[i]);
             * }
             *          packetListView.ItemsSource = _thepackets;
             */


            tcp       = new TcpSocketClient();
            udp       = new UdpSocketClient();
            thepacket = new Packet();

            MessagingCenter.Subscribe <LoginPage, List <Packet> >(this, Events.NEW_PACKET_LIST, OnNewPacketListAsync);
            MessagingCenter.Subscribe <ImportCloud, List <Packet> >(this, Events.NEW_PACKET_LIST, OnNewPacketListAsyncIC);
            MessagingCenter.Subscribe <PacketEditPage, Packet>(this, Events.PACKET_MODIFIED, OnPacketModified);
        }