protected void RunMessageReceiver(CancellationToken cancelToken) { var observeUdpReceive = Observable.While( () => !cancelToken.IsCancellationRequested, Observable.FromAsync(BackingUdpClient.ReceiveAsync)) .Select(msg => { var message = new UdpMessage { ByteData = msg.Buffer, RemotePort = msg.RemoteEndPoint.Port.ToString(), RemoteAddress = msg.RemoteEndPoint.Address.ToString() }; return(message); }); observeUdpReceive.Subscribe( // Message Received Args (OnNext) args => { _messageSubject.OnNext(args); }, // Exception (OnError) ex => throw ((NativeSocketExceptions.Contains(ex.GetType())) ? new SocketException(ex) : ex), cancelToken); }
public async Task JoinMulticastGroupAsync( string multicastAddress, int port, ICommunicationInterface communicationInterface = null, bool allowMultipleBindToSamePort = false) { CheckCommunicationInterface(communicationInterface); var ipAddress = (communicationInterface as CommunicationInterface)?.NativeIpAddress ?? IPAddress.Any; var ipEndPoint = new IPEndPoint(ipAddress, port); InitializeUdpClient(ipEndPoint, allowMultipleBindToSamePort); MessageConcellationTokenSource = new CancellationTokenSource(); var multicastIp = IPAddress.Parse(multicastAddress); try { BackingUdpClient.JoinMulticastGroup(multicastIp, TTL); } catch (Exception ex) { throw (NativeSocketExceptions.Contains(ex.GetType())) ? new PclSocketException(ex) : ex; } _multicastAddress = multicastAddress; _multicastPort = port; await Task.Run(() => RunMessageReceiver(MessageConcellationTokenSource.Token)).ConfigureAwait(false); }
protected IObservable <IUdpMessage> CreateObservableMessageStream(CancellationTokenSource cancelToken) { _cancellationTokenSource = cancelToken; var observable = Observable.Create <IUdpMessage>( obs => { var disp = Observable.While( () => !cancelToken.Token.IsCancellationRequested, Observable.FromAsync(BackingUdpClient.ReceiveAsync)) .Select(msg => { var message = new UdpMessage { ByteData = msg.Buffer, RemotePort = msg.RemoteEndPoint.Port.ToString(), RemoteAddress = msg.RemoteEndPoint.Address.ToString() }; return(message); }).Subscribe( msg => obs.OnNext(msg), ex => { Cleanup(); var getEx = NativeSocketExceptions.Contains(ex.GetType()) ? new SocketException(ex) : ex;; obs.OnError(getEx); }, () => { Cleanup(); cancelToken.Cancel(); }); return(disp); }); return(observable); }
private Exception NativeException(Exception ex) { throw NativeSocketExceptions.Contains(ex.GetType()) ? new SocketException(ex) : ex; }