/// <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; })); }
private static void HandleSearchResponseMessage(string message, IObserver <SearchResponseMessage> observer) { logger.Instance().Trace("Received search response message", "Message".As(message)); try { var responseMessage = SearchResponseMessage.Create(message); observer.OnNext(responseMessage); } catch (ArgumentException ex) { logger.Instance().Warning(ex, "The received M-Search response has been ignored.", "Message".As(message)); } }