private bool CanConnect(IPEndPoint ep) { bool allowed = false; IncomingConnection?.Invoke(ep, out allowed); return(allowed); }
public void IncomingConnection_DoesNothing() { // Arrange var connection = new IncomingConnection(); // Assert Assert.IsNull(connection.FromNeuron); }
private async Task AwaitConnection(TcpListener tcpListener) { TcpClient client = await tcpListener.AcceptTcpClientAsync(); LogConnection(client); IncomingConnection?.Invoke(this, new IncomingConnectionArgs { Client = client }); }
private IEnumerator <object> KeepAliveTask(ListenerContext context, IncomingConnection incomingConnection) { var socket = incomingConnection.Socket; EndPoint localEp = socket.LocalEndPoint, remoteEp = socket.RemoteEndPoint; var evtArgs = new ConnectionEventArgs(localEp, remoteEp); var keepAliveStarted = DateTime.UtcNow; if (SocketOpened != null) { SocketOpened(this, evtArgs); } int requestCount = 0; try { using (var adapter = new SocketDataAdapter(socket, true)) { while (!adapter.IsDisposed && adapter.Socket.Connected) { var fTask = Scheduler.Start(RequestTask(context, adapter)); yield return(fTask); requestCount += 1; if (fTask.Failed) { adapter.Dispose(); yield break; } } } } finally { var keepAliveEnded = DateTime.UtcNow; if (SocketClosed != null) { SocketClosed(this, evtArgs); } if (Trace != null) { Trace( String.Format( "KA_START {0:0000.0}ms KA_LENGTH {1:00000.0}ms {2} REQ(S)", (keepAliveStarted - incomingConnection.AcceptedWhenUTC).TotalMilliseconds, (keepAliveEnded - keepAliveStarted).TotalMilliseconds, requestCount ) ); } } }
private void Listen() { while (true) { TcpClient client = listener.AcceptTcpClient(); var connection = new TcpConnection(client); var args = new IncomingConnectionEventArgs { Connection = connection }; IncomingConnection?.Invoke(this, args); } }
public void GetOutgoingConnections_WithoutOutgoingConnections_ReturnsEmpty() { // Arrange IHiddenNeuron hiddenNeuron = new HiddenNeuron(); IIncomingConnection inConnection = new IncomingConnection(hiddenNeuron); _neuron.Connections.Add(inConnection); // Act var outConnections = _neuron.GetOutgoingConnections(); // Assert Assert.IsTrue(outConnections.Count() == 0); }
public void GetIncomingConnections_WithIncomingConnections_ReturnsConnections() { // Arrange IHiddenNeuron hiddenNeuron = new HiddenNeuron(); IIncomingConnection inConnection = new IncomingConnection(hiddenNeuron); _neuron.Connections.Add(inConnection); // Act var inConnections = _neuron.GetIncomingConnections(); // Assert Assert.IsTrue(inConnections.Count() == 1); Assert.IsTrue(inConnections.First() == inConnection); }
/// <summary> /// Kills this connection /// </summary> /// <param name="softKill">If true will perform a shutdown before closing, otherwise close will happen with lingering disabled</param> public void Kill(bool softKill) { if (softKill) { // Soft close, do shutdown first IncomingConnection.Shutdown(SocketShutdown.Both); } else { // Hard close - force no lingering IncomingConnection.LingerState = new LingerOption(true, 0); } IncomingConnection.Dispose(); OutgoingConnection.Dispose(); }
private void ListenForConnections(TcpListener listener) { Task.Factory.StartNew(async() => { try { while (isListeningForIncomingConnections) { var client = await listener.AcceptTcpClientAsync(); var reader = new StreamReader(client.GetStream()); var status = reader.ReadLine(); string remoteDestination = status.Split(' ').First(); IncomingConnection?.Invoke(this, new AcceptConnectionEventArgs(client, remoteDestination)); } } finally { listener.Stop(); } }, TaskCreationOptions.LongRunning); }
/// <summary> /// Handles the bidirectional data transfers /// </summary> private void _ProcessorHandler() { try { Server.Log("Connecting to {0}...", Server.RemoteEndpoint); Server.Log("Remote end point address family {0}", Server.RemoteEndpoint.AddressFamily); // Establish outgoing connection to the proxy OutgoingConnection = new Socket(Server.RemoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); Task connectTask = OutgoingConnection.ConnectAsync(Server.RemoteEndpoint.Address, Server.RemoteEndpoint.Port); connectTask.Wait(1000); // Writing connection information Server.Log("Connection established"); // Obtain network streams NetworkStream outStream = new NetworkStream(OutgoingConnection, true); NetworkStream inStream = new NetworkStream(IncomingConnection, true); // Ensure copying isn't paused Server.PermitCopying.Wait(); // Tunnel the traffic between two connections while (IncomingConnection.Connected && OutgoingConnection.Connected && !Server.StopRequested) { bool DataAvailable = false; // Check incoming buffer if (inStream.DataAvailable) { DataAvailable = true; CopyData(inStream, "client", outStream, "server", Server.SimulatedInDelay); } // Check outgoing buffer if (outStream.DataAvailable) { DataAvailable = true; CopyData(outStream, "server", inStream, "client", Server.SimulatedOutDelay); } // Pause if (DataAvailable) { // Poll the sockets if ((IncomingConnection.Poll(100, SelectMode.SelectRead) && !inStream.DataAvailable) || (OutgoingConnection.Poll(100, SelectMode.SelectRead) && !outStream.DataAvailable)) { break; } Thread.Sleep(10); } else { Thread.Sleep(1); } // Ensure copying isn't paused Server.PermitCopying.Wait(); } } catch (Exception ex) { Server.Log(ex.ToString()); } try { // Disconnect the client IncomingConnection.Dispose(); OutgoingConnection.Dispose(); } catch (Exception) { } // Logging disconnection message Server.Log("Connection closed"); // Notify parent Server.NotifyClientDisconnection(this); }
/// <summary> /// Handles the bidirectional data transfers /// </summary> private void _ProcessorHandler() { try { Server.Log("Connecting to {0}...", Server.RemoteEndpoint); Server.Log("Remote end point address family {0}", Server.RemoteEndpoint.AddressFamily); // Establish outgoing connection to the proxy OutgoingConnection = new TcpClient(Server.RemoteEndpoint.AddressFamily); OutgoingConnection.Connect(Server.RemoteEndpoint); // Writing connection information Server.Log("Connection established"); // Obtain network streams NetworkStream outStream = OutgoingConnection.GetStream(); NetworkStream inStream = IncomingConnection.GetStream(); // Tunnel the traffic between two connections while (IncomingConnection.Connected && OutgoingConnection.Connected && !Server.StopRequested) { // Check incoming buffer if (inStream.DataAvailable) { CopyData(inStream, "client", outStream, "server", Server.SimulatedInDelay); } // Check outgoing buffer if (outStream.DataAvailable) { CopyData(outStream, "server", inStream, "client", Server.SimulatedOutDelay); } // Poll the sockets if ((IncomingConnection.Client.Poll(100, SelectMode.SelectRead) && !inStream.DataAvailable) || (OutgoingConnection.Client.Poll(100, SelectMode.SelectRead) && !outStream.DataAvailable)) { break; } Thread.Sleep(10); } } catch (Exception ex) { Server.Log(ex.ToString()); } try { // Disconnect the client IncomingConnection.Close(); OutgoingConnection.Close(); } catch (Exception) { } // Logging disconnection message Server.Log("Connection closed"); // Notify parent Server.NotifyClientDisconnection(this); }
internal IncomingConnectionEventArgs(IncomingConnection connection) { Connection = connection; ConnectionAccepted = false; }
private IEnumerator<object> KeepAliveTask(ListenerContext context, IncomingConnection incomingConnection) { var socket = incomingConnection.Socket; EndPoint localEp = socket.LocalEndPoint, remoteEp = socket.RemoteEndPoint; var evtArgs = new ConnectionEventArgs(localEp, remoteEp); var keepAliveStarted = DateTime.UtcNow; if (SocketOpened != null) SocketOpened(this, evtArgs); int requestCount = 0; try { using (var adapter = new SocketDataAdapter(socket, true)) { while (!adapter.IsDisposed && adapter.Socket.Connected) { var fTask = Scheduler.Start(RequestTask(context, adapter)); yield return fTask; requestCount += 1; if (fTask.Failed) { adapter.Dispose(); yield break; } } } } finally { var keepAliveEnded = DateTime.UtcNow; if (SocketClosed != null) SocketClosed(this, evtArgs); if (Trace != null) Trace( String.Format( "KA_START {0:0000.0}ms KA_LENGTH {1:00000.0}ms {2} REQ(S)", (keepAliveStarted - incomingConnection.AcceptedWhenUTC).TotalMilliseconds, (keepAliveEnded - keepAliveStarted).TotalMilliseconds, requestCount ) ); } }
private void SetupUnity() { try { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json"); this.container .RegisterInstance < IConfigurationRoot>(configurationBuilder.Build()) .RegisterSingleton < IBodyReconstructorFactory <string>, JsonBodyReconstructorFactory>() .RegisterSingleton < IEnvelopFactory <PayloadType, string>, JsonEnvelopeFactory <PayloadType> >() .RegisterSingleton < IMessageResultFactory <string>, JsonMessageResultFactory>() .RegisterSingleton < IEncoder <PayloadType, string>, StringBodyEncoder <PayloadType> >() .RegisterSingleton < IJsonSetting, JsonSettings>() .RegisterSingleton < IOutgoingConnection <PayloadType, string>, OutgoingConnection <PayloadType, string> >() .RegisterSingleton < IConnectionIdGenerator, ConnectionIdGenerator>() .RegisterSingleton < IIncomingMessageBuilder <PayloadType, string>, IncomingMessageBuilder <PayloadType, string> >() .RegisterSingleton < IMessageRouter <PayloadType, string, MessageCtx <PayloadType, string> >, MessageRouter <PayloadType, string, MessageCtx <PayloadType, string> > >() .RegisterSingleton < IRequestIdGenerator, RequestIdGenerator>() .RegisterSingleton < IMessageStore <PayloadType, string, MessageCtx <PayloadType, string> >, InMemoryMessageStore <PayloadType, string, MessageCtx <PayloadType, string> > >() .RegisterSingleton < IIncomingMessageHandler <PayloadType, string>, IncomingMessageProcessor <PayloadType, string, MessageCtx <PayloadType, string> > >() .RegisterSingleton <IncomingConnection <PayloadType, string, MessageCtx <PayloadType, string> > >() .RegisterSingleton < IEncoder <PayloadType, string>, StringBodyEncoder <PayloadType> >() .RegisterSingleton < INetMqConfig, NetMqConfig>() .RegisterSingleton < IPayloadTypeEncoder <PayloadType, string>, PayloadTypeEncoder>() .RegisterSingleton < IMessageSetting, MessagingSetting>() ; this.outgoingConnection = this.container.Resolve <IOutgoingConnection <PayloadType, string> >(); this.incomingConnection = this.container .Resolve <IncomingConnection <PayloadType, string, MessageCtx <PayloadType, string> > >(); this.incomingMessageHandler = this.container .Resolve <IIncomingMessageHandler <PayloadType, string> >(); } catch (Exception ex) { log.Error(ex, ex.Message); throw; } }