/// <summary> /// A callback function when data is send to the socket. /// </summary> /// <param name="ar"><see cref="IAsyncResult"/>.</param> protected virtual void SendCallback(IAsyncResult ar) { if (ar is null) { throw new ArgumentNullException(nameof(ar)); } // Retrieve the socket from the state object. if (ar.AsyncState is not Socket client) { Logger.LogCritical("No Socket was passed to the send function"); return; } try { // Complete sending the data to the remote device. var bytesSent = client.EndSend(ar); } catch (Exception ex) { Logger.LogError(ex, "Failed sending data to {RemoteEndPoint}", client.RemoteEndPoint); ConnectionState.OnNext(Connected.No(this)); } }
/// <inheritdoc/> protected override void Shutdown() { try { if (Socket == null) { Logger.LogDebug("No connection to close"); return; } if (!Socket.Connected) { Logger.LogDebug("Connection is already closed"); Socket = null; return; } Logger.LogDebug("Closing connection"); Socket.Disconnect(false); ConnectionState.OnNext(Connected.No(this)); Logger.LogInformation("{RemoteEndpoint} Connection closed", Socket.RemoteEndPoint); Socket.Close(); Socket = null; } catch (ObjectDisposedException ex) { Logger.LogDebug(ex, "Connection is already closed"); } catch (Exception ex) { Logger.LogError(ex, "Failed shutting down socket"); } }
private void ConnectCallback(IAsyncResult ar) { try { Logger.LogTrace("Retrieving the socket from the state object"); if (ar.AsyncState is not Socket client) { Logger.LogCritical("No socket was passed as state object!"); return; } Logger.LogTrace("Complete the connection."); client.EndConnect(ar); Logger.LogInformation("Connected to: {RemoteEndpoint}", client.RemoteEndPoint); ConnectionState.OnNext(Connected.Yes(this)); var state = new StateObject(client); Logger.LogDebug("Start listening for new messages"); _ = client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ReceiveCallback, state); } catch (Exception ex) { Socket = null; Logger.LogError(ex, $"Connect failed"); ConnectionState.OnNext(Connected.No(this)); } }
public BrokerConnection(string uri, string realm) { var channel = new WampChannelFactory() .ConnectToRealm(realm) .WebSocketTransport(new Uri(uri)) .JsonSerialization() .Build(); async Task Connect() { Log.Information("Trying to connect to broker {brokerUri}", uri); try { await channel.Open(); Log.Debug("Connection Opened."); _subject.OnNext(Connected.Yes(new Broker(channel))); } catch (Exception exception) { Log.Error(exception, "Connection Failed."); _subject.OnNext(Connected.No <IBroker>()); throw; } } _reconnector = new WampChannelReconnector(channel, Connect); }
public BrokerConnection(string uri, string realm) { _channel = new WampChannelFactory() .ConnectToRealm(realm) .WebSocketTransport(uri) .JsonSerialization() .Build(); Func <Task> connect = async() => { Log.InfoFormat("Trying to connect to broker {0}", uri); try { await _channel.Open(); Log.Debug("Connection Opened."); _subject.OnNext(Connected.Yes(new Broker(_channel))); } catch (Exception) { Log.Debug("Connection Failed."); _subject.OnNext(Connected.No <IBroker>()); throw; } }; _reconnector = new WampChannelReconnector(_channel, connect); }
public static IObservable <IConnected <IEventStoreConnection> > GetEventStoreConnectedStream(this ConnectionStatusMonitor monitor, IEventStoreConnection connection) { return(monitor.ConnectionInfoChanged.Where(x => x.Status == ConnectionStatus.Connected || x.Status == ConnectionStatus.Disconnected) .Select(c => c.Status == ConnectionStatus.Connected ? Connected.Yes(connection) : Connected.No <IEventStoreConnection>())); }
/// <summary> /// A callback function when data is received from the socket. /// </summary> /// <param name="ar"><see cref="IAsyncResult"/>.</param> protected virtual void ReceiveCallback(IAsyncResult ar) { // Retrieve the state object and the client socket // from the asynchronous state object. if (ar.AsyncState is not StateObject state) { Logger.LogCritical("No StateObject was passed to the state object"); return; } var socket = state.WorkSocket; EndPoint?remoteEndPoint = null; try { remoteEndPoint = socket.RemoteEndPoint; // Read data from the remote device. var bytesRead = socket.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. for (var i = 0; i < bytesRead; i++) { state.RawBytes.Add(state.Buffer[i]); } if (socket.Available == 0) { var receivedData = new ReceivedData(state.RawBytes.ToArray(), socket); dataReceived.OnNext(receivedData); Logger.LogDebug("Received: {Message} - From: {RemoteEndpoint}", receivedData.Message, remoteEndPoint); state.RawBytes.Clear(); } // Get the rest of the data. _ = socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } else { Logger.LogInformation("{RemoteEndpoint} requested a shutdown", remoteEndPoint); Shutdown(); } } catch (Exception ex) { Logger.LogError(ex, "Failed receiving data from {RemoteEndpoint}", remoteEndPoint); ConnectionState.OnNext(Connected.No(this)); } }
public void Start() { var brokerStartingTime = 4; while (brokerStartingTime-- > 0 && _connection == null) { try { _connection = _connectionFactory.CreateConnection(); } catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException) { Thread.Sleep(2000); } } if (_connection == null) { throw new RabbitMQ.Client.Exceptions.BrokerUnreachableException(null); } _channel = _connection.CreateModel(); _sessionDispose.Add(_connection); _sessionDispose.Add(_channel); _subject.OnNext(Connected.Yes(new Broker(_channel))); _connection.RecoverySucceeded += (obj, evt) => { Log.Debug("Connection recovered."); _subject.OnNext(Connected.Yes(new Broker(_channel))); }; _connection.ConnectionRecoveryError += (obj, evt) => { Log.Error(evt.Exception, "Connection Failed."); _subject.OnNext(Connected.No <IBroker>()); }; }
/// <summary> /// Initializes a new instance of the <see cref="EthernetConnection"/> class. /// </summary> /// <param name="logger">An <see cref="ILogger"/> instance used for logging.</param> public EthernetConnection(ILogger <EthernetConnection> logger) : base(logger) { Socket = null; ConnectionState.OnNext(Connected.No(this)); }
public IObservable <IConnected <IRabbitMqConnection> > GetConnectionStatus() { return(_connectionInfoChanged .Where(connectionInfo => connectionInfo.Status == ConnectionStatus.Connected || connectionInfo.Status == ConnectionStatus.Disconnected) .Select(connectionInfo => { return connectionInfo.Status == ConnectionStatus.Connected ? Connected.Yes(_rabbitMqConnection) : Connected.No <IRabbitMqConnection>(); })); }
/// <summary> /// Initializes a new instance of the <see cref="Ethernet"/> class. /// </summary> /// <param name="logger">An <see cref="ILogger"/> instance used for logging.</param> public Ethernet(ILogger logger) { Logger = logger; ConnectionState = new BehaviorSubject <IConnected <IEthernetConnection> >(Connected.No <IEthernetConnection>(null)); }