JoinMulticastGroup() public method

public JoinMulticastGroup ( [ host ) : void
host [
return void
Exemplo n.º 1
0
        private async void Init()
        {
            _Listener = new DatagramSocket();
            _Listener.MessageReceived += Listener_MessageReceived;

            while (true)
            {
                try
                {
                    await _Listener.BindServiceNameAsync("6");
                    break;
                }
                catch (COMException)
                {
                    var messageDialog = new MessageDialog("Only one usage of each port is normally permitted.\r\n\r\nIs 'Windows IoT Core Watcher' open?", "Port in use");
                    messageDialog.Commands.Add(new UICommand("Try again", (command) => { }));
                    await messageDialog.ShowAsync();
                }
            }

            HostName hostname = new HostName("239.0.0.222");
            _Listener.JoinMulticastGroup(hostname);

            _Settings = ApplicationData.Current.LocalSettings;

            _Timer = new Timer(Timer_Callback, null, 1000, 1000);
        }
Exemplo n.º 2
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());
			}
		}
Exemplo n.º 3
0
        public async Task Open()
        {
            //CheckBackgroundTask();
            //await CheckSocketAsync();

            #region Simple socket creation
            if (listenerSocket == null)
            {
                listenerSocket = new DatagramSocket();
                listenerSocket.Control.DontFragment = true;
                listenerSocket.Control.MulticastOnly = true;
                listenerSocket.MessageReceived += DataReceived;

                try
                {
                    await listenerSocket.BindServiceNameAsync(localService);
                    listenerSocket.JoinMulticastGroup(new HostName(remoteMulticastAddress));
                }
                catch (Exception exception)
                {
                    Close();

                    // If this is an unknown status it means that the error is fatal and retry will likely fail.
                    if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                        throw;

                    //rootPage.NotifyUser("Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage);
                }
            }
            #endregion
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initialize the connection to the network (prepare sockets, join multicast group, handle the right events, etc)
        /// </summary>
        /// <returns></returns>
        public void InitializeSockets()
        {
            if (Initialized)
                return;

            MulticastAddress = new HostName(MulticastAddressStr);
            // To receive packets (either unicast or multicast), a MessageReceived event handler must be defined

            // Initialize the multicast socket and register the event
            MulticastSocket = new DatagramSocket();
            MulticastSocket.MessageReceived += MulticastSocketMessageReceived;

            // bind to a local UDP port
            MulticastSocket.BindServiceNameAsync(MulticastPortStr).AsTask().Wait();

            // Call the JoinMulticastGroup method to join the multicast group.
            MulticastSocket.JoinMulticastGroup(MulticastAddress);

            // Get our IP address
            String MyIPString = PeerConnector.GetMyIP();
            myIPAddress = new HostName(MyIPString);

            // Construct a list of ip addresses that should be ignored
            IgnoreableNetworkAddresses = new List<String> { LinkLocalPrefixString, LocalLoopbackPrefixString, PrivateNetworkPrefixString }; //, MyIPString };
            System.Diagnostics.Debug.WriteLine("Ignored IP Addresses: " + LinkLocalPrefixString + " - " + LocalLoopbackPrefixString + " - " + PrivateNetworkPrefixString);

            TCPListener = new TCPSocketListener("80085", new TCPRequestHandler(ProcessNetworkObject));
            TCPSocketHelper = new TCPSocketClient("80085");
            TCPListener.Start();

            Initialized = true;
        }
		private async Task ExecuteDiscoveryTask()
		{
			int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2;

			while (running)
			{
				Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Started Cloudlet Discovery using Multicast UDP");
				retry = 0;

				DatagramSocket socketSent = null;
				DatagramSocket socketReplay = null;
				try
				{
					socketSent = new DatagramSocket();
					await socketSent.BindEndpointAsync(null, string.Empty);
					socketSent.JoinMulticastGroup(ip);

					socketReplay = new DatagramSocket();
					socketReplay.MessageReceived += SocketOnMessageReceived;
					await socketReplay.BindServiceNameAsync(replyCloudletPort.ToString());

					using (DataWriter writer = new DataWriter(await socketSent.GetOutputStreamAsync(ip, multicastPort.ToString())))
					{
						while (retry < 60 && running)
						{
							writer.WriteString("mpos_cloudlet_req");
							await writer.StoreAsync();
							await writer.FlushAsync();

							await Task.Delay(500);
							retry++;
						}
					}
				}
				catch (IOException e)
				{
					Debug.WriteLine("## [DiscoveryCloudletMulticast]: Any problem with i/o in multicast system!\n" + e.ToString());
				}
				finally
				{
					socketSent.Dispose();
					socketReplay.Dispose();

					socketSent = null;
					socketReplay = null;
				}

				if (running)
				{
					Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms");
					await Task.Delay(repeatTime);
				}
				else
				{
					Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet");
				}
			}
		}
Exemplo n.º 6
0
    /// <summary>
    /// Returns list of bridge IPs
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<string>> LocateBridgesAsync(TimeSpan timeout)
    {
      if (timeout <= TimeSpan.Zero)
        throw new ArgumentException("Timeout value must be greater than zero.", "timeout");

      var discoveredDevices = new List<string>();
      var multicastIP = new HostName("239.255.255.250");
      
      using (var socket = new DatagramSocket())
      {

        //Handle MessageReceived
        socket.MessageReceived += (sender, e) =>
        {
          var reader = e.GetDataReader();
          var bytesRemaining = reader.UnconsumedBufferLength;
          var receivedString = reader.ReadString(bytesRemaining);

          var location = receivedString.Substring(receivedString.ToLower().IndexOf("location:", System.StringComparison.Ordinal) + 9);
          receivedString = location.Substring(0, location.IndexOf("\r", System.StringComparison.Ordinal)).Trim();

          discoveredDevices.Add(receivedString);
        };

        await socket.BindEndpointAsync(null, string.Empty);
        socket.JoinMulticastGroup(multicastIP);

        var start = DateTime.Now;

        do
        {
          using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
          using (var writer = new DataWriter(stream))
          {
            string request = "M-SEARCH * HTTP/1.1\r\n" +
                         "HOST:239.255.255.250:1900\r\n" +
                         //"ST:urn:schemas-upnp-org:device:Basic:1\r\n" + //Alternative
                         // "ST:upnp:rootdevice\r\n" +                    //Alternative
                         "ST:SsdpSearch:all\r\n" +
                         "MAN:\"ssdp:discover\"\r\n" +
                         "MX:3\r\n\r\n\r\n";

            writer.WriteString(request.ToString());
            await writer.StoreAsync();

          }

        }
        while (DateTime.Now.Subtract(start) < timeout); // try for thee seconds
      }

      return await FilterBridges(discoveredDevices);

    }
Exemplo n.º 7
0
        private async Task<DatagramSocket> ListenForTick(NetworkAdapter hostname)
        {
            var socket = new DatagramSocket();
            socket.MessageReceived += OnMessageReceived;

            await socket.BindServiceNameAsync(Settings.RemoteServiceName, hostname);
            socket.JoinMulticastGroup(new HostName(Settings.MulticastAddress));

            Log($"Listening on {hostname.NetworkAdapterId}:{Settings.RemoteServiceName}");

            return socket;
        }
 private async Task SendTick()
 {
     using (var socket = new DatagramSocket())
     {
         await socket.BindServiceNameAsync(string.Empty);
         socket.JoinMulticastGroup(new HostName(BroadcastAddress));
         var outputStream =
             await socket.GetOutputStreamAsync(new HostName(BroadcastAddress), RemoteServiceName);
         var buffer = Encoding.UTF8.GetBytes("TT_SEND_DEVICE_INFO");
         await outputStream.WriteAsync(buffer.AsBuffer());
         await outputStream.FlushAsync();
         Debug.WriteLine("TICK Broadcasted to {0}:{1}", BroadcastAddress, RemoteServiceName);
     }
 }
        /// <summary>
        /// Start listening.
        /// </summary>
        public override async Task<bool> StartListeningAsync()
        {
            bool status = false;

            if (_listenerSocket == null)
            {
                _listenerSocket = new DatagramSocket();
                _listenerSocket.MessageReceived += AdvertisementMessageReceivedFromManagerAsync;
                await _listenerSocket.BindServiceNameAsync(ListenerPort);
                _listenerSocket.JoinMulticastGroup(ListenerGroupHost);

                status = true;
            }

            return status;
        }
Exemplo n.º 10
0
 public override async void Start()
 {
     if (Status == ListenerStatus.Listening)
         return;
     try
     {
         _datagramSocket = new DatagramSocket();
         _datagramSocket.MessageReceived += DatagramSocketOnMessageReceived;
         await _datagramSocket.BindServiceNameAsync(MulticastPort.ToString());
         _datagramSocket.JoinMulticastGroup(MulticastIpAddress);
         RaiseStatusChanged(ListenerStatus.Listening);
     }
     catch
     {
         RaiseStatusChanged(ListenerStatus.PortNotFree);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// @see http://www.johnthom.com/implementing-ssdp-search-in-windows-phone-8-using-winrt/
        /// </summary>
        public async Task DiscoverDevices()
        {
            int timeout = 3000;
            var remoteIp = "239.255.255.250";
            var remoteIpHostName = new Windows.Networking.HostName(remoteIp);
            var port = "1900";

            string query = "M-SEARCH * HTTP/1.1\r\n" +
                         "HOST: 239.255.255.250:1900\r\n" +
                         "ST: upnp:rootdevice\r\n" +
                         "MAN: \"ssdp:discover\"\r\n" +
                         "MX: " + timeout.ToString() + "\r\n\r\n";

            var buffer = Encoding.UTF8.GetBytes(query);

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += (sender, args) => {
                    Task.Run(() => {
                        using (var reader = args.GetDataReader())
                        {
                            byte[] respBuff = new byte[reader.UnconsumedBufferLength];
                            reader.ReadBytes(respBuff);
                            string response = Encoding.UTF8.GetString(respBuff, 0, respBuff.Length).ToLower();
                            response.Trim('\0');

                            ProcessSSDPResponse(response);
                        }
                    });
                };

                await socket.BindEndpointAsync(null, "");
                socket.JoinMulticastGroup(remoteIpHostName);
                
                using (var stream = await socket.GetOutputStreamAsync(remoteIpHostName, port))
                {
                    await stream.WriteAsync(buffer.AsBuffer());
                }
                
                // Execute within timeout
                await Task.Delay(timeout);
            }
        }
Exemplo n.º 12
0
        public async void FindTvs()
        {
            if (searchState == SearchState.Searching)
            {
                StopSearching();
            }

            tvSearchSocket = new DatagramSocket();
            tvSearchSocket.MessageReceived += TvListenCompleted;
            await tvSearchSocket.BindEndpointAsync(null, "");
            tvSearchSocket.JoinMulticastGroup(multicastAddress);
            StartedSearching();
            SendSSDP();

            tvSearchRetryTimer = new Timer(TvSearchRetry, null, TimeSpan.FromSeconds(tvSearchRetryTimeSeconds), TimeSpan.FromMilliseconds(-1));
            tvSearchTimeoutTimer = new Timer(TvSearchTimeout, null, TimeSpan.FromSeconds(tvSearchTotalTimeSeconds), TimeSpan.FromMilliseconds(-1));

            searchState = SearchState.Searching;
        }
Exemplo n.º 13
0
 public static IObservable<ZeroconfRecord> Resolve(string protocol)
 {
     return Observable.Create<ZeroconfRecord>(async observer =>
         {
             var socket = new DatagramSocket();
             var s = Observable
                 .FromEventPattern
                 <TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>,
                     DatagramSocketMessageReceivedEventArgs>(
                         x => socket.MessageReceived += x, _ => socket.Dispose())
                 .Select(ProcessMessage)
                 .Where(x => x != null)
                 .Subscribe(observer);
             await socket.BindServiceNameAsync("5353");
             socket.JoinMulticastGroup(new HostName("224.0.0.251"));
             var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353");
             var writer = new DataWriter(os);
             WriteQueryMessage(protocol, writer);
             writer.StoreAsync();
             return s;
         });
 }
        public async Task<bool> StartupAsync(string multicastIP, int multicastPort)
        {
            await ShutdownAsync();
            IsRunning = true;

            this.MulticastIP = multicastIP;
            this.MulticastPort = multicastPort;

            try
            {
                socket = new DatagramSocket();
                socket.MessageReceived += socket_MessageReceived;
                await socket.BindEndpointAsync(null, multicastPort.ToString());
                socket.JoinMulticastGroup(new HostName(multicastIP));
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("{0} occurred while starting multicast listener: {1}", ex.GetType().Name, ex.Message));
                await ShutdownAsync();
                return false;
            }
        }
Exemplo n.º 15
0
        private async Task CheckSocketAsync()
        {
            try
            {
                SocketActivityInformation socketInformation;
                if (!SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
                {
                    var socket = new DatagramSocket();
                    socket.Control.DontFragment = true;
                    socket.Control.MulticastOnly = true;
                    socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.Wake);

                    await socket.BindServiceNameAsync(localService);
                    socket.JoinMulticastGroup(new HostName(remoteMulticastAddress));

                    // To demonstrate usage of CancelIOAsync async, have a pending read on the socket and call 
                    // cancel before transfering the socket. 
                    //DataReader reader = new DataReader(socket.InputStream);
                    //reader.InputStreamOptions = InputStreamOptions.Partial;
                    //var read = reader.LoadAsync(250);
                    //read.Completed += (info, status) =>
                    //{
                    //};
                    //await socket.CancelIOAsync();

                    socket.TransferOwnership(socketId);
                    socket = null;
                }
                //rootPage.NotifyUser("Connected. You may close the application", NotifyType.StatusMessage);
            }
            catch (Exception exception)
            {
                //rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
            }
        }
        /// <summary>
        /// This is the click handler for the 'StartListener' button.
        /// </summary>
        /// <param name="sender">Object for which the event was generated.</param>
        /// <param name="e">Event's parameters.</param>
        private async void StartListener_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(ServiceName.Text))
            {
                rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage);
                return;
            }

            if (listenerSocket != null)
            {
                rootPage.NotifyUser("A listener socket is already set up.", NotifyType.ErrorMessage);
                return;
            }

            bool isMulticastSocket = (MulticastRadioButton.IsChecked == true);
            listenerSocket = new DatagramSocket();
            listenerSocket.MessageReceived += MessageReceived;

            if (isMulticastSocket)
            {
                // DatagramSockets conduct exclusive (SO_EXCLUSIVEADDRUSE) binds by default, effectively blocking
                // any other UDP socket on the system from binding to the same local port. This is done to prevent
                // other applications from eavesdropping or hijacking a DatagramSocket's unicast traffic.
                //
                // Setting the MulticastOnly control option to 'true' enables a DatagramSocket instance to share its
                // local port with any Win32 sockets that are bound using SO_REUSEADDR/SO_REUSE_MULTICASTPORT and
                // with any other DatagramSocket instances that have MulticastOnly set to true. However, note that any
                // attempt to use a multicast-only DatagramSocket instance to send or receive unicast data will result
                // in an exception being thrown.
                //
                // This control option is particularly useful when implementing a well-known multicast-based protocol,
                // such as mDNS and UPnP, since it enables a DatagramSocket instance to coexist with other applications
                // running on the system that also implement that protocol.
                listenerSocket.Control.MulticastOnly = true;
            }

            // Start listen operation.
            try
            {
                await listenerSocket.BindServiceNameAsync(ServiceName.Text);

                if (isMulticastSocket)
                {
                    // Join the multicast group to start receiving datagrams being sent to that group.
                    listenerSocket.JoinMulticastGroup(new HostName(RemoteAddress.Text));

                    rootPage.NotifyUser(
                        "Listening on port " + listenerSocket.Information.LocalPort + " and joined to multicast group",
                        NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser(
                        "Listening on port " + listenerSocket.Information.LocalPort,
                        NotifyType.StatusMessage);
                }

                // Enable scenario steps that require us to have an active listening socket.
                SendMessageButton.IsEnabled = true;
                CloseListenerButton.IsEnabled = true;
            }
            catch (Exception exception)
            {
                listenerSocket.Dispose();
                listenerSocket = null;

                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                rootPage.NotifyUser(
                    "Start listening failed with error: " + exception.Message,
                    NotifyType.ErrorMessage);
            }
        }
Exemplo n.º 17
0
        private static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
            await socket.BindServiceNameAsync("5353")
                        .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();
            }
        }
Exemplo n.º 18
0
        private static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
#if !WINDOWS_PHONE
            try
            {
               // Try to bind using port 5353 first
               await socket.BindServiceNameAsync("5353", NetworkInformation.GetInternetConnectionProfile().NetworkAdapter)
                           .AsTask(cancellationToken)
                           .ConfigureAwait(false);

            }
            catch (Exception)
            {
                // If it fails, use the default
                await socket.BindServiceNameAsync("", NetworkInformation.GetInternetConnectionProfile().NetworkAdapter)
                            .AsTask(cancellationToken)
                            .ConfigureAwait(false);

            }
#else
            await socket.BindServiceNameAsync("5353")
                        .AsTask(cancellationToken)
                        .ConfigureAwait(false);

#endif
                        

            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();
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Search devices and retrieve their device info.
        /// </summary>
        /// <param name="timeoutSec">Seconds to wait before invokation of OnTimeout.</param>
        /// <param name="OnServerFound">Success callback. This will be invoked for each devices until OnTimeout is invoked.</param>
        /// <param name="OnTimeout">Timeout callback.</param>
        public async void SearchDevices(int timeoutSec, Action<DeviceInfo> OnServerFound, Action OnTimeout)
        {
            if (OnServerFound == null || OnTimeout == null)
            {
                throw new ArgumentNullException();
            }

            Debug.WriteLine("DeviceFinder.SearchDevices");

            if (timeoutSec < 2)
            {
                timeoutSec = 2;
            }

            const int MX = 1;

            var ssdp_data = new StringBuilder()
                .Append("M-SEARCH * HTTP/1.1").Append("\r\n")
                .Append("HOST: ").Append(multicast_address).Append(":").Append(ssdp_port.ToString()).Append("\r\n")
                .Append("MAN: ").Append("\"ssdp:discover\"").Append("\r\n")
                .Append("MX: ").Append(MX.ToString()).Append("\r\n")
                .Append("ST: urn:schemas-sony-com:service:ScalarWebAPI:1").Append("\r\n")
                //.Append("ST: ssdp:all").Append("\r\n") // For debug
                .Append("\r\n")
                .ToString();
            byte[] data_byte = Encoding.UTF8.GetBytes(ssdp_data);
            //Debug.WriteLine(ssdp_data);

            bool timeout_called = false;

            var DD_Handler = new AsyncCallback(ar =>
            {
                if (timeout_called)
                {
                    return;
                }

                var req = ar.AsyncState as HttpWebRequest;

                try
                {
                    var res = req.EndGetResponse(ar) as HttpWebResponse;
                    using (var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
                    {
                        try
                        {
                            var info = AnalyzeDD(reader.ReadToEnd());
                            NotifyFoundAsync(info, OnServerFound);
                        }
                        catch (Exception)
                        {
                            //Invalid XML.
                        }
                    }
                }
                catch (WebException)
                {
                    //Invalid DD location or network error.
                }
            });

#if WINDOWS_PHONE
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SendBufferSize = data_byte.Length;

            SocketAsyncEventArgs snd_event_args = new SocketAsyncEventArgs();
            snd_event_args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(multicast_address), ssdp_port);
            snd_event_args.SetBuffer(data_byte, 0, data_byte.Length);

            SocketAsyncEventArgs rcv_event_args = new SocketAsyncEventArgs();
            rcv_event_args.SetBuffer(new byte[result_buffer], 0, result_buffer);

            var SND_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.SendTo)
                {
                    socket.ReceiveBufferSize = result_buffer;
                    socket.ReceiveAsync(rcv_event_args);
                }
            });
            snd_event_args.Completed += SND_Handler;

            var RCV_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.Receive)
                {
                    string result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
                    //Debug.WriteLine(result);

                    GetDDAsync(DD_Handler, result);

                    socket.ReceiveAsync(e);
                }
            });
            rcv_event_args.Completed += RCV_Handler;
            socket.SendToAsync(snd_event_args);
#elif NETFX_CORE
            var sock = new DatagramSocket();
            sock.MessageReceived += (sender, args) =>
            {
                if (timeout_called || args == null)
                {
                    return;
                }
                var reader = args.GetDataReader();
                string data = reader.ReadString(reader.UnconsumedBufferLength);
                Debug.WriteLine(data);

                GetDDAsync(DD_Handler, data);
            };
            try
            {
                await sock.BindServiceNameAsync(ssdp_port.ToString());
            }
            catch (Exception)
            {
                Debug.WriteLine("Duplicate search is not supported");
                return;
            }
            var host = new HostName(multicast_address);
            sock.JoinMulticastGroup(host);
            try
            {
                var output = await sock.GetOutputStreamAsync(host, ssdp_port.ToString());
                await output.WriteAsync(data_byte.AsBuffer());
                await sock.OutputStream.FlushAsync();
            }
            catch (Exception)
            {
                Debug.WriteLine("Failed to send multicast");
                return;
            }
#endif

            await RunTimeoutInvokerAsync(timeoutSec, () =>
            {
                Debug.WriteLine("SSDP Timeout");
                timeout_called = true;
#if WINDOWS_PHONE
                snd_event_args.Completed -= SND_Handler;
                rcv_event_args.Completed -= RCV_Handler;
                socket.Close();
#elif NETFX_CORE
                sock.Dispose();
#endif
                OnTimeout.Invoke();
            });
        }
Exemplo n.º 20
0
		/// <summary>
		///     Searches for an available devices of specified type.
		/// </summary>
		/// <param name="searchTarget">
		///     The type of the devices to search for.
		/// </param>
		/// <param name="timeForResponse">
		///     The time (in seconds) of a search.
		/// </param>
		/// <returns>
		///     An observable collection which contains search results.
		/// </returns>
		public IObservable<SearchResponseMessage> Search(string searchTarget, int timeForResponse)
		{
			return Observable.Create<SearchResponseMessage>(async observer =>
			{
				var searchSocket = new DatagramSocket();

				// Handling responses from found devices
				searchSocket.MessageReceived += async (sender, args) =>
				{
					var dataReader = args.GetDataReader();
					dataReader.InputStreamOptions = InputStreamOptions.Partial;

					if (dataReader.UnconsumedBufferLength == 0)
					{
						await dataReader.LoadAsync(1024);
					}

					var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);

					try
					{
						var response = SearchResponseMessage.Create(message);

						observer.OnNext(response);
					}
					catch (ArgumentException ex)
					{
						logger.Instance().Warning(ex, "The received M-Search response has been ignored.", "Message".As(message));
					}
				};

				await searchSocket.BindServiceNameAsync("0");
				searchSocket.JoinMulticastGroup(this.multicastHost);

				var request = MSearchRequestFormattedString.F(searchTarget, timeForResponse);
				var buffer = Encoding.UTF8.GetBytes(request).AsBuffer();

				// Sending the search request to a multicast group
				var outputStream = await searchSocket.GetOutputStreamAsync(this.multicastHost, MulticastPort.ToString());
				await outputStream.WriteAsync(buffer);
				await outputStream.WriteAsync(buffer);

				// Stop listening for a devices when timeout for responses is expired
				Observable.Timer(TimeSpan.FromSeconds(timeForResponse)).Subscribe(s =>
				{
					observer.OnCompleted();
					searchSocket.Dispose();
				});

				logger.Instance().Debug("M-Search request has been sent. [multicastHost={0}, searchTarget={1}]".F(multicastHost.DisplayName, searchTarget));
				return searchSocket.Dispose;
			});
		}
        /// <summary>
        /// initialize multicast
        /// </summary>
        private async void multi_cast()
        {
            listenerSocket = new DatagramSocket();              //datagram object
            listenerSocket.MessageReceived += MessageReceived;  //MessageReceived event 
            //listenerSocket.MessageReceived += MessageReceived;
            listenerSocket.Control.MulticastOnly = true;

            //datagram service name
            await listenerSocket.BindServiceNameAsync("22113");
            //Datagram group IP
            listenerSocket.JoinMulticastGroup(new HostName("224.3.0.5"));


        }
Exemplo n.º 22
0
        private async void Search(string st, TimeSpan? timeout = null)
        {
            Log("Search");

            var ssdp_data = new StringBuilder()
                .Append("M-SEARCH * HTTP/1.1").Append("\r\n")
                .Append("HOST: ").Append(MULTICAST_ADDRESS).Append(":").Append(SSDP_PORT.ToString()).Append("\r\n")
                .Append("MAN: ").Append("\"ssdp:discover\"").Append("\r\n")
                .Append("MX: ").Append(MX.ToString()).Append("\r\n")
                .Append("ST: ").Append(st).Append("\r\n")
                .Append("\r\n")
                .ToString();
            var data_byte = Encoding.UTF8.GetBytes(ssdp_data);

            var timeout_called = false;

#if WINDOWS_PHONE||DOT_NET
            var DD_Handler = new AsyncCallback(ar =>
            {
                if (timeout_called)
                {
                    return;
                }

                var req = ar.AsyncState as HttpWebRequest;

                try
                {
                    var res = req.EndGetResponse(ar) as HttpWebResponse;
                    using (var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
                    {
                        try
                        {
                            var response = reader.ReadToEnd();
                            OnDiscovered(new DeviceDescriptionEventArgs(response));

                            var camera = AnalyzeDescription(response);
                            if (camera != null)
                            {
                                OnDiscovered(new SonyCameraDeviceEventArgs(camera, req.RequestUri));
                            }
                        }
                        catch (Exception)
                        {
                            Log("Invalid XML");
                            //Invalid XML.
                        }
                    }
                }
                catch (WebException)
                {
                    //Invalid DD location or network error.
                }
            });
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SendBufferSize = data_byte.Length;

            var snd_event_args = new SocketAsyncEventArgs();
            snd_event_args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(MULTICAST_ADDRESS), SSDP_PORT);
            snd_event_args.SetBuffer(data_byte, 0, data_byte.Length);

            var rcv_event_args = new SocketAsyncEventArgs();
            rcv_event_args.SetBuffer(new byte[RESULT_BUFFER], 0, RESULT_BUFFER);

            var SND_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.SendTo)
                {
                    try
                    {
                        socket.ReceiveBufferSize = RESULT_BUFFER;
                        socket.ReceiveAsync(rcv_event_args);
                    }
                    catch (ObjectDisposedException)
                    {
                        Log("Socket is already disposed.");
                    }
                }
            });
            snd_event_args.Completed += SND_Handler;

            var RCV_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.Receive)
                {
                    string result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
                    //Log(result);

                    GetDeviceDescriptionAsync(DD_Handler, result);

                    try
                    {
                        socket.ReceiveAsync(e);
                    }
                    catch (ObjectDisposedException)
                    {
                        Log("Socket is already disposed.");
                    }
                }
            });
            rcv_event_args.Completed += RCV_Handler;
            socket.SendToAsync(snd_event_args);
#elif WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
            var handler = new TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>(async (sender, args) =>
            {
                Log("Datagram message received");
                if (timeout_called || args == null)
                {
                    return;
                }
                string data;
                using (var reader = args.GetDataReader())
                {
                    data = reader.ReadString(reader.UnconsumedBufferLength);
                }
                Log(data);
                await GetDeviceDescriptionAsync(data, args.LocalAddress).ConfigureAwait(false);
            });

            var adapters = await GetActiveAdaptersAsync().ConfigureAwait(false);

            await Task.WhenAll(adapters.Select(async adapter =>
            {
                using (var socket = new DatagramSocket())
                {
                    socket.Control.DontFragment = true;
                    socket.MessageReceived += handler;

                    try
                    {
                        await socket.BindServiceNameAsync("", adapter);
                        socket.JoinMulticastGroup(MULTICAST_HOST);

                        using (var output = await socket.GetOutputStreamAsync(MULTICAST_HOST, SSDP_PORT.ToString()))
                        {
                            using (var writer = new DataWriter(output))
                            {
                                writer.WriteBytes(data_byte);
                                await writer.StoreAsync();
                            }
                        }
                        await Task.Delay((timeout == null) ? DEFAULT_TIMEOUT : timeout.Value).ConfigureAwait(false);
                        Log("Search Timeout");
                        timeout_called = true;
                    }
                    catch (Exception e)
                    {
                        Log("Failed to send multicast: " + e.StackTrace);
                    }
                    finally
                    {
                        socket.MessageReceived -= handler;
                    }
                }
            })).ConfigureAwait(false);
#endif
#if WINDOWS_PHONE||DOT_NET
            await Task.Delay((timeout == null) ? DEFAULT_TIMEOUT : timeout.Value).ConfigureAwait(false);

            Log("Search Timeout");
            timeout_called = true;
            snd_event_args.Completed -= SND_Handler;
            rcv_event_args.Completed -= RCV_Handler;
            socket.Close();
#endif
            OnTimeout(new EventArgs());
        }
Exemplo n.º 23
0
        public async Task DiscoverBridge(TimeSpan timeOut)
        {
            var multicastIP = new HostName("239.255.255.250");
            var foundBridge = false;

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += async (sender, args) =>
                {
                    var reader = args.GetDataReader();
                    var bytesRemaining = reader.UnconsumedBufferLength;
                    foreach (var line in reader.ReadString(bytesRemaining).Split(new String[1] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("LOCATION"))
                        {
                            var address = line.Split(new char[1] { ':' }, 2)[1];
                            var message = await _client.GetAsync(address);
                            
                            if (message.IsSuccessStatusCode)
                            {
                                var messageContent = await message.Content.ReadAsStringAsync();
                                var buffer = Encoding.UTF8.GetBytes(messageContent);
                                
                                
                            }
                        }
                    }

                    foundBridge = true;
                };

                await socket.BindEndpointAsync(null, string.Empty);
                socket.JoinMulticastGroup(multicastIP);

                while(true)
                {
                    foundBridge = false;

                    using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
                    using (var writer = new DataWriter(stream))
                    {
                        var request = new StringBuilder();
                        request.AppendLine("M-SEARCH * HTTP/1.1");
                        request.AppendLine("HOST: 239.255.255.250:1900");
                        request.AppendLine("MAN: ssdp:discover");
                        request.AppendLine("MX: 3");
                        request.AppendLine("ST: ssdp:all");

                        writer.WriteString(request.ToString());
                        await writer.StoreAsync();

                        if (timeOut > TimeSpan.Zero)
                        {
                            await Task.Delay(timeOut);
                        }
                            
                        if (foundBridge)
                        {
                            break;
                        }
                    }
                }
            }

        }
Exemplo n.º 24
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;
        }