using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KnockKnock.Lib { internal class ConnectionPool { public delegate void PoolEvent(ConnectionPool sender); public event PoolEvent Closed; List connections; public ConnectionPool() { connections = new List(); } public void Open() { foreach (Connection c in this.connections) { c.Open(); } } public void AddConnection(Connection c) { this.connections.Add(c); c.Received += Connection_Receive; c.Closed += Connection_Closed; } public void RemoveConnection(Connection c) { this.connections.Remove(c); c.Received -= Connection_Receive; c.Closed -= Connection_Closed; } public void Close() { foreach (Connection c in this.connections) { c.Close(); } } protected void Connection_Receive(Connection sender, byte[] data) { System.Diagnostics.Debug.WriteLine("Receive " + data.Length + " bytes"); foreach (Connection c in this.connections) { if (c != sender) { System.Diagnostics.Debug.WriteLine("Send " + data.Length + " bytes"); c.Send(data); } } } protected void Connection_Closed(Connection sender) { System.Diagnostics.Debug.WriteLine("Closed"); foreach (Connection c in this.connections) { if (c != sender) { c.Close(); } } Closed(this); } } }