using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace KnockKnock.Lib { public class Proxy { public delegate void ProxyEvent(Proxy sender); public event ProxyEvent Active; public event ProxyEvent Idle; Listener listener; Upstream upstream; List connections; public Proxy(IPEndPoint listener, IPEndPoint upstream) { this.listener = new Listener(listener.Port); this.upstream = new Upstream(upstream.Address, upstream.Port); this.connections = new List(); } public void Start() { this.listener.Connected += Listener_Connected; this.listener.Start(); } public void Stop() { foreach (ConnectionPool p in connections) { p.Close(); } connections.Clear(); } private void Listener_Connected(Listener sender, Socket client_socket) { if (this.connections.Count == 0 && this.Active != null) { this.Active(this); } Socket upstream_socket = this.upstream.Connect(); Connection client_conn = new Connection(client_socket); Connection upstream_conn = new Connection(upstream_socket); ConnectionPool cp = new ConnectionPool(); cp.AddConnection(client_conn); cp.AddConnection(upstream_conn); cp.Closed += Connection_Closed; cp.Open(); } private void Connection_Closed(ConnectionPool sender) { connections.Remove(sender); if (connections.Count == 0 && this.Idle != null) { this.Idle(this); } } } }