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 { internal class Connection { public delegate void SocketReceivedEvent(Connection sender, byte[] data); public delegate void SocketEvent(Connection sender); public SocketReceivedEvent Received; public SocketEvent Closed; const int BUFFER_SIZE = 1024; Socket socket; byte[] buffer = new byte[BUFFER_SIZE]; public Connection(Socket socket) { this.socket = socket; } public void Open() { this.socket.BeginReceive(this.buffer, 0, BUFFER_SIZE, SocketFlags.None, this.SocketReceive, null); } public void Close() { this.socket.Close(); } public void Send(byte[] data) { try { this.socket.Send(data); } catch { this.Closed(this); } } protected void SocketReceive(IAsyncResult result) { int read; try { read = socket.EndReceive(result); } catch { Closed(this); return; } if (read == 0) { // Connection closed Closed(this); } else { byte[] received = new byte[read]; Array.Copy(this.buffer, 0, received, 0, read); Received(this, received); try { socket.BeginReceive(this.buffer, 0, BUFFER_SIZE, SocketFlags.None, this.SocketReceive, null); } catch { Closed(this); } } } } }