Example #1
0
 public async Task <bool> InitializeRecv()
 {
     recvInitialized = false;
     try
     {
         if (msocketRecv != null)
         {
             msocketRecv.MessageReceived -= UDPMulticastMessageReceived;
             msocketRecv.Dispose();
             msocketRecv = null;
         }
         msocketRecv = new DatagramSocket();
         msocketRecv.MessageReceived += UDPMulticastMessageReceived;
         NetworkAdapter adapter = GetDefaultNetworkAdapter();
         if (adapter != null)
         {
             await msocketRecv.BindServiceNameAsync(mPort);
         }
         //              await msocketRecv.BindServiceNameAsync(mPort, adapter);
         else
         {
             await msocketRecv.BindServiceNameAsync(mPort);
         }
         HostName mcast = new HostName(mAddress);
         msocketRecv.JoinMulticastGroup(mcast);
         mLastIDReceived = 0;
         recvInitialized = true;
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
         recvInitialized = false;
     }
     return(recvInitialized);
 }
Example #2
0
 async Task <bool> InitializeMulticastRecv()
 {
     try
     {
         if (msocketRecv != null)
         {
             msocketRecv.MessageReceived -= UDPMulticastMessageReceived;
             msocketRecv.Dispose();
             msocketRecv = null;
         }
         msocketRecv = new DatagramSocket();
         msocketRecv.Control.MulticastOnly = true;
         msocketRecv.MessageReceived      += UDPMulticastMessageReceived;
         NetworkAdapter adapter = GetDefaultNetworkAdapter(SendInterfaceAddress);
         if (adapter != null)
         {
             await msocketRecv.BindServiceNameAsync(MulticastUDPPort.ToString(), adapter);
         }
         else
         {
             await msocketRecv.BindServiceNameAsync(MulticastUDPPort.ToString());
         }
         HostName mcast = new HostName(MulticastIPAddress);
         msocketRecv.JoinMulticastGroup(mcast);
         return(true);
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
     }
     return(false);
 }
Example #3
0
        /// <summary>
        /// Initiates the Discovery System Client.
        /// </summary>
        /// <param name="name">This is the port the system will listen for and broadcast udp packets</param>
        /// <param name="deviceInfo">A JSON object containing all the relevant device info</param>
        public override async void Initialize(string name, object deviceInfo)
        {
            Debug.WriteLine($"Discovery System: Initializing {name}");

            try
            {
                // Set the device name
                this.name = name;

                // Set initial variables
                DeviceInfo = deviceInfo;

                // Setup a UDP socket listener
                socket.MessageReceived += ReceivedDiscoveryMessage;
                await socket.BindServiceNameAsync(udpPort.ToString());

                // Tell the world you exist
                SendDiscoveryResponseMessage();

                // Find out who else is out there
                Discover();

                // Set up the rest API
                InitializeRestApi(tcpPort);

                Debug.WriteLine("Discovery System: Success");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Discovery System: Failure");
                Debug.WriteLine("Reason: " + ex.Message);
            }
        }
Example #4
0
 public async Task Bind()
 {
     if (string.IsNullOrEmpty(_datagram.Information.LocalPort))
     {
         await _datagram.BindServiceNameAsync(_port.ToString());
     }
 }
Example #5
0
        async Task <bool> InitializeUnicastRecv()
        {
            try
            {
                if (usocketRecv != null)
                {
                    usocketRecv.MessageReceived -= UDPUnicastMessageReceived;
                    usocketRecv.Dispose();
                    usocketRecv = null;
                }
                usocketRecv = new DatagramSocket();
                usocketRecv.MessageReceived += UDPUnicastMessageReceived;
                //  NetworkAdapter adapter = GetDefaultNetworkAdapter();
                //  if (adapter != null)
                //      await msocketRecv.BindServiceNameAsync(UnicastUDPPort.ToString(), adapter);
                //  else
                await usocketRecv.BindServiceNameAsync(UnicastUDPPort.ToString());

                return(true);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception while listening: " + e.Message);
            }
            return(false);
        }
Example #6
0
        public async Task <bool> InitializeSend()
        {
            sendInitialized = false;
            try
            {
                if (msocketSend != null)
                {
                    //    msocketSend.MessageReceived -= UDPMulticastMessageReceived;
                    msocketSend.Dispose();
                    msocketSend = null;
                }
                msocketSend = new DatagramSocket();
                //  msocketSend.MessageReceived += UDPMulticastMessageReceived;

                NetworkAdapter adapter = GetDefaultNetworkAdapter();
                if (adapter != null)
                {
                    await msocketSend.BindServiceNameAsync("", adapter);
                }
                mLastIDSent     = 0;
                sendInitialized = true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception while initializing: " + e.Message);
                sendInitialized = false;
            }
            return(sendInitialized);
        }
Example #7
0
        async Task <bool> InitializeSend()
        {
            bool result = false;

            try
            {
                if (msocketSend != null)
                {
                    msocketSend.Dispose();
                    msocketSend = null;
                }
                msocketSend = new DatagramSocket();

                NetworkAdapter adapter = GetDefaultNetworkAdapter(SendInterfaceAddress);
                if (adapter != null)
                {
                    await msocketSend.BindServiceNameAsync("", adapter);
                }
                result = true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception while initializing: " + e.Message);
                result = false;
            }
            return(result);
        }
        private async void CreateSocketsAsync()
        {
            receivingUdp = new DatagramSocket();
            receivingUdp.MessageReceived += ReceivingUdp_MessageReceived;

            await receivingUdp.BindServiceNameAsync(UDPListenerPort.ToString());
        }
Example #9
0
        public static async void init(TiSettings settings)
        {
            if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0)
            {
                return;
            }

            logToken = settings["logToken"];

            multicastSocket = new DatagramSocket();
            multicastSocket.MessageReceived += multicastSocket_MessageReceived;

            HostName hostname = new HostName("239.6.6.6");

            try {
                await multicastSocket.BindServiceNameAsync("8666");

                multicastSocket.JoinMulticastGroup(hostname);

                IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666");

                DataWriter writer = new DataWriter(stream);
                writer.WriteString("TI_WP8_LOGGER");
                await writer.StoreAsync();

                writer.DetachStream();
                stream.Dispose();
            } catch (Exception ex) {
                if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
                Debug.WriteLine(ex.ToString());
            }
        }
        public static async Task ConnectAsync(string hostName = HOST_NAME, string port = REMOTE_PORT)
        {
            if (!StubMode)
            {
#if WINDOWS_APP || WINDOWS_PHONE_APP
                // Set up the UDP connection.
                var droneIP = new HostName(hostName);

                udpSocket = new DatagramSocket();
                await udpSocket.BindServiceNameAsync(port);

                await udpSocket.ConnectAsync(droneIP, port);

                udpWriter = new DataWriter(udpSocket.OutputStream);

                udpWriter.WriteByte(1);
                await udpWriter.StoreAsync();
#else
                udpSocket = new UdpClient();
                udpSocket.Connect(hostName, int.Parse(port));

                byte[] datagram = new byte[1] {
                    1
                };
                await udpSocket.SendAsync(datagram, datagram.Length);
#endif
            }

            var loop = Task.Run(() => DroneLoop());
        }
Example #11
0
        private async void FindHostIP()
        {
            //Open up a socket
            _listener = new DatagramSocket();

            //Add MessageReceived Event
            _listener.MessageReceived += MessageReceived;

            //Important for async access
            CoreApplication.Properties.Add("listener", _listener);

            // Start listen operation.
            try
            {
                UpdateUi("Finding Ev3 IP Address.. Please Wait");
                _listener.Control.InboundBufferSizeInBytes = _EV3_INBOUND_BUFFER_SIZE;

                //Await Message
                await _listener.BindServiceNameAsync(_EV3_PORT);
            }
            catch (Exception e)
            {
                UpdateUi(" Connection Error " + e.Message);
            }
        }
Example #12
0
        public UdpNetworkListenManager(int port)
        {
#if UNITY_UWP
            Task.Run(async() =>
            {
                socket = new DatagramSocket();
                socket.MessageReceived += MessageReceived;
                await socket.BindServiceNameAsync(port.ToString());
            });
#elif UNITY_EDITOR || UNITY_STANDALONE
            thread = new Thread(() => {
                ListenFlag                      = true;
                UdpClient udpclient             = new UdpClient(port);
                udpclient.Client.ReceiveTimeout = 100;
                IPEndPoint remote               = new IPEndPoint(IPAddress.Any, port);
                while (ListenFlag)
                {
                    try
                    {
                        byte[] bytes = udpclient.Receive(ref remote);
                        if (UdpNetworkListenEvent != null)
                        {
                            UdpNetworkListenEvent(Encoding.UTF8.GetString(bytes), remote.Address.ToString());
                        }
                    }
                    catch (Exception) { }
                }
                udpclient.Close();
            });
            thread.Start();
#endif
        }
Example #13
0
 /// <summary>
 /// Starts the listening for Udp-Broadcast Packets.
 /// </summary>
 public async void GetRobotUriAsync()
 {
     _listener = new DatagramSocket();
     _listener.Control.InboundBufferSizeInBytes = 100;
     _listener.MessageReceived += Listener_MessageReceived;
     await _listener.BindServiceNameAsync(_port.ToString());
 }
        public async void InitializeSockets()
        {
            if (SocketsAreConnected)
            {
                return;
            }

            ab  = new DatagramSocket();
            scr = new DatagramSocket();

            ab.MessageReceived  += ClientSocketMessageReceived;
            scr.MessageReceived += ClientSocketMessageReceived2;
            try
            {
                await ab.BindServiceNameAsync("11444");

                await scr.BindServiceNameAsync("11445");
            }
            catch (Exception exception)
            {
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                // DebugLogOut("Error: Start Listen failed: " + exception.Message);
                return;
            }

            SocketsAreConnected = true;
        }
Example #15
0
        //Bind socket to port
        public bool Bind(ref NetEndPoint ep)
        {
            _datagramSocket = new DatagramSocket();
            _datagramSocket.Control.DontFragment = true;
            _datagramSocket.MessageReceived     += OnMessageReceived;

            try
            {
                if (ep.HostName == null)
                {
                    _datagramSocket.BindServiceNameAsync(ep.PortStr).GetResults();
                }
                else
                {
                    _datagramSocket.BindEndpointAsync(ep.HostName, ep.PortStr).GetResults();
                }

                ep = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort);
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Example #16
0
        private async void StartUDPServer(string port)
        {
            var serverDatagramSocket = new DatagramSocket();

            serverDatagramSocket.MessageReceived += ServerDatagramSocket_MessageReceived;
            await serverDatagramSocket.BindServiceNameAsync(port);
        }
Example #17
0
        static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
#if WINDOWS_UWP
            // Set control option for multicast. This enables re-use of the port, which is always in use under Windows 10 otherwise.
            socket.Control.MulticastOnly = true;
#endif
            await socket.BindServiceNameAsync("5353") // binds to the local IP addresses of all network interfaces on the local computer if no adapter is specified
            .AsTask(cancellationToken)
            .ConfigureAwait(false);

            socket.JoinMulticastGroup(new HostName("224.0.0.251"));
            var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353")
                     .AsTask(cancellationToken)
                     .ConfigureAwait(false);

            using (var writer = new DataWriter(os))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync()
                .AsTask(cancellationToken)
                .ConfigureAwait(false);

                Debug.WriteLine("Sent mDNS query");

                writer.DetachStream();
            }
        }
        public override async void Start()
        {
            if (_Started)
            {
                return;
            }
            _SequenceNumber = 1;

            try
            {
                // Connect to the Drone
                udpClient = new DatagramSocket();
                await udpClient.BindServiceNameAsync(_ServiceName);

                await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);

                udpWriter = new DataWriter(udpClient.OutputStream);

                udpWriter.WriteByte(1);
                await udpWriter.StoreAsync();

                _Timer   = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
                _Started = true;
            }
            catch (Exception)
            {
                Stop();
            }
        }
        public FalconOperationResult TryStart()
        {
            try
            {
                datagramSocket = new DatagramSocket();

                SetEF();

                datagramSocket.MessageReceived += OnMessageReceived;

                // HACK: We know this is not an async op and will be run in-line so avoid breaking our API
                //       and "wait" for op to complete.
                //
                var asyncOp = datagramSocket.BindServiceNameAsync(localPeer.Port.ToString());
                var task    = asyncOp.AsTask();
                task.Wait();

                return(FalconOperationResult.SuccessResult);
            }
            catch (AggregateException aex)
            {
                // e.g. address already in use
                return(new FalconOperationResult(aex.InnerExceptions.Count > 0 ? aex.InnerExceptions[0] : aex));
            }
        }
Example #20
0
        private async void ConnectUdpReceive_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (receiveSocket == null)
                {
                    receiveSocket = new DatagramSocket();

                    // MessageReceived handler must be set before BindServiceAsync is called, if not
                    // "A method was called at an unexpected time. (Exception from HRESULT:
                    // 0x8000000E)" exception is thrown.
                    receiveSocket.MessageReceived += OnMessageReceived;

                    // If port is already in used by another socket, "Only one usage of each socket
                    // address (protocol/network address/port) is normally permitted. (Exception from
                    // HRESULT: 0x80072740)" exception is thrown.
                    await receiveSocket.BindServiceNameAsync("2704");

                    DisplayOutput(UdpReceiveOutput, "Connected (bound).");
                }
            }
            catch (Exception ex)
            {
                DisplayOutput(UdpReceiveOutput, ex.ToString());
            }
        }
Example #21
0
    public async void StartListening()
    {
        if (IsListening)
        {
            return;
        }

        IsListening = true;

        socket = new DatagramSocket();
        socket.Control.MulticastOnly = false;
        socket.MessageReceived      += SocketOnMessageReceived;

        try
        {
            await socket.BindServiceNameAsync(listenPort.ToString());

            HostName remoteHost = new HostName("255.255.255.255");

            IOutputStream outputStream = await socket.GetOutputStreamAsync(remoteHost, listenPort.ToString());

            DataWriter writer = new DataWriter(outputStream);
            writer.WriteString("1");
            await writer.StoreAsync();
        }
        catch (Exception e) { }
    }
Example #22
0
        public IAsyncAction Start()
        {
            return(Task.Run(async() =>
            {
                if (isStarted)
                {
                    return;
                }

                multicastSsdpSocket = new DatagramSocket();
                multicastSsdpSocket.MessageReceived += MulticastSsdpSocket_MessageReceived;
                multicastSsdpSocket.Control.MulticastOnly = true;
                await multicastSsdpSocket.BindServiceNameAsync(Constants.SSDP_PORT);
                multicastSsdpSocket.JoinMulticastGroup(Constants.SSDP_HOST);

                unicastLocalSocket = new DatagramSocket();
                unicastLocalSocket.MessageReceived += UnicastLocalSocket_MessageReceived;
                await unicastLocalSocket.BindServiceNameAsync("");
                logger.WriteLine($"ControlPoint: Bind to port :{unicastLocalSocket.Information.LocalPort} for UNICAST search responses.");

                NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

                networks = GetNetworks();

                isStarted = true;

                logger.WriteLine("ControlPoint started.");
            }).AsAsyncAction());
        }
Example #23
0
        public override async void Start()
        {
            if (_Started)
            {
                return;
            }
            _SequenceNumber = 1;

            // Connect To Drone
            udpClient = new DatagramSocket();
            await udpClient.BindServiceNameAsync(_ServiceName);

            await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);

            udpWriter = new DataWriter(udpClient.OutputStream);

            //string path = string.Format("AR.Drone-CommandHistory_{0:yyyy-MM-dd-HH-mm}.txt", DateTime.Now);
            //commandHistoryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
            // Write first message
            //byte[] firstMessage = BitConverter.GetBytes(1);
            //WriteString(firstMessage.ToString());

            udpWriter.WriteByte(1);
            await udpWriter.StoreAsync();

            _Timer   = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
            _Started = true;
        }
        /// <summary>
        /// This is only used by Webfront class. Thus only one listen Port while multiple send ports
        /// are used by Curtain Motor and light dimmers
        /// </summary>
        public void Initialise()
        {
            //Initialise the Automation Objects
            //Add the Automation Objects
            for (int i = 0; i < Constants.ROOMS; i++)
            {
                //Add Temperature Monitor Objects
                TemperatureMonitor tm = new TemperatureMonitor();
                tm.EstablishConnection(Constants.TemperatureMonitorAddress[i], Constants.TEMPSOCKET);
                Temperatures.Add(tm);

                //Add Intruder Detectors
                IntruderDetect detector = new IntruderDetect();
                detector.EstablishConnection(Constants.IntruderDetectAddress[i], Constants.INTRUDERSOCKET);
                Detectors.Add(detector);
            }

            //Initialise the buffer for storing Temperatures strings
            temperatureAlerts = new string[Constants.ROOMS];

            for (int i = 0; i < Constants.ROOMS; i++)
            {
                temperatureAlerts[i] = "No Connectivity to Room: " + (i + 1).ToString() + "\n";
            }
            GuestSocket.MessageReceived += MessageReceivedAsync;
            GuestSocket.BindServiceNameAsync(Constants.LISTENPORT).AsTask().Wait();
        }
Example #25
0
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            Send.IsEnabled = false;
            var socket = new DatagramSocket();

            try
            {
                var    address = Address.Text.Split(':');
                string host = address[0], port = address[1];
                await socket.BindServiceNameAsync("1902");

                var outputStream = await socket.GetOutputStreamAsync(new HostName(host), port);

                var writer = new DataWriter(outputStream);
                writer.WriteString(Message.Text);
                await writer.StoreAsync();

                socket.Dispose();
            }
            catch (Exception ex)
            {
                logger.WriteLine(ex.ToString());
            }
            finally
            {
                socket.Dispose();
                Send.IsEnabled = true;
            }
        }
Example #26
0
        private async Task JitterCalculation()
        {
            datagramSocket = new DatagramSocket();

            datagramSocket.MessageReceived += delegate(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
            {
                System.Diagnostics.Debug.WriteLine("[ProfileNetworkFull]: Jitter Finish");
            };

            string port = server.JitterTestPort.ToString();
            await datagramSocket.BindServiceNameAsync(port);

            using (DataWriter writer = new DataWriter(await datagramSocket.GetOutputStreamAsync(hostName, port)))
            {
                for (int i = 0; i < 21; i++)
                {
                    writer.WriteString("jitter");
                    await writer.StoreAsync();

                    await writer.FlushAsync();

                    await Task.Delay(250);
                }
            }

            Close(ref datagramSocket);
        }
Example #27
0
        public static async Task Init()
        {
            ClearPrevious();

            try
            {
                if (App.isRPi)
                {
                    await InitCamera(1, IMAGE_QUALITY_PERCENT, VIDEO_SUBTYP, VIDEO_RES);

                    socket = new DatagramSocket();
                    socket.MessageReceived += MessageReceived;
                    HostName hn = new HostName(hostName);
                    await socket.ConnectAsync(hn, hostPort).AsTask();

                    Debug.WriteLine("Connected to remote camera " + hn + ":" + hostPort);
                    socketIsConnected = true;
                }
                else
                {
                    listener = new DatagramSocket();
                    listener.MessageReceived += MessageReceived;
                    await listener.BindServiceNameAsync(hostPort).AsTask();

                    Debug.WriteLine("Remote camera listening on port " + hostPort);
                    listenerHasStarted = true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error initializing camera: " + ex.Message);
            }
        }
Example #28
0
        private async Task Connect()
        {
            if (_isBound || _isBinding)
            {
                return;
            }

            lock (_lock)
            {
                if (_isBound || _isBinding)
                {
                    return;
                }

                _isBinding = true;
            }

            var possibleConnectionProfiles = NetworkInformation.GetConnectionProfiles()
                                             .Where(p => p.IsWlanConnectionProfile && p.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)
                                             .ToList();

            var connectionProfile = possibleConnectionProfiles.FirstOrDefault();

            if (connectionProfile != null)
            {
                await _socket.BindServiceNameAsync(_ipAddress.ServiceName, connectionProfile.NetworkAdapter);
            }

            _isBound   = true;
            _isBinding = false;
        }
Example #29
0
        public DiscoveryServerService(ISettingsService settingsService)
        {
            _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));

            _socket.MessageReceived += SendResponseAsync;
            _socket.BindServiceNameAsync(Port.ToString()).GetAwaiter().GetResult();
        }
Example #30
0
        public async void ConnectUDP(NetworkConnectionEndpoint remoteNetworkConnectionEndpoint)
        {
            if (!IsUDPSetup)
            {
                InitUDP();
            }
            if (IsUDPConnected)
            {
                ResetUDP(); InitUDP();
            }

            try
            {
                Debug.WriteLine("Binding UDPPort");
                await m_datagramSocket.BindServiceNameAsync(remoteNetworkConnectionEndpoint.Port);

                Debug.WriteLine("Connecting UDPSocket");
                await m_datagramSocket.ConnectAsync(remoteNetworkConnectionEndpoint.HostName, remoteNetworkConnectionEndpoint.Port);

                Debug.WriteLine("Creating UDPDataWriter");
                m_udpDataWriter = new DataWriter(m_datagramSocket.OutputStream);

                Debug.WriteLine("Completed UDP");
                UDPNetworkConnectionEndpoint = remoteNetworkConnectionEndpoint;
                IsUDPConnected = true;

                Debug.WriteLine("UDP Connected: " + UDPNetworkConnectionEndpoint.ToString());
            }
            catch (Exception ex) { Debug.WriteLine(DebugTools.PrintOutException("ConnectUDP", ex)); }
        }
Example #31
0
        public bool Bind(int port)
        {
            _datagramSocket = new DatagramSocket();
            _datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize;
            _datagramSocket.Control.DontFragment = true;
            _datagramSocket.Control.OutboundUnicastHopLimit = NetConstants.SocketTTL;
            _datagramSocket.MessageReceived += OnMessageReceived;

            try
            {
                _datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait();
                _datagramSocket.JoinMulticastGroup(MulticastAddressV6);
                _localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort);
            }
            catch (Exception ex)
            {
                NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
                return false;
            }
            return true;
        }