Created
September 16, 2015 17:47
-
-
Save georgebearden/fa4e5f57dab5af62fdb7 to your computer and use it in GitHub Desktop.
An example of a singleton rx observable that will notify when a socket is connected/disconnected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public enum SocketStates | |
| { | |
| Unknown, | |
| Up, | |
| Down | |
| } | |
| public class SocketWatcher : IObservable<SocketStates>, IDisposable | |
| { | |
| private readonly BehaviorSubject<SocketStates> _socketState = new BehaviorSubject<SocketStates>(SocketStates.Unknown); | |
| private bool _running = true; | |
| public SocketWatcher(string host, int port) | |
| { | |
| Task.Run( async () => | |
| { | |
| SocketStates prevState = SocketStates.Unknown; | |
| while ( _running ) | |
| { | |
| var currState = await IsConnected( host, port ); | |
| if (prevState != currState) | |
| { | |
| _socketState.OnNext( currState ); | |
| prevState = currState; | |
| } | |
| await Task.Delay( 1000 ); | |
| } | |
| } ); | |
| } | |
| public void Dispose() | |
| { | |
| _running = false; | |
| } | |
| public IDisposable Subscribe( IObserver<SocketStates> observer ) | |
| { | |
| return _socketState.Subscribe( observer ); | |
| } | |
| public async static Task<SocketStates> IsConnected(string host, int port) | |
| { | |
| var tcpClient = new TcpClient(); | |
| var cancelToken = new CancellationTokenSource( 1000 ); | |
| await Task.Run( () => | |
| { | |
| try | |
| { | |
| tcpClient.Connect( host, port ); | |
| } | |
| catch (Exception) | |
| { | |
| } | |
| }, cancelToken.Token ); | |
| return tcpClient.Connected ? SocketStates.Up : SocketStates.Down; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment