// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; namespace E { public class AClient { private Socket cli; private byte[] buf; private int buflen; public AClient(Socket cli, AServer srv) { Console.WriteLine("Connection open from " + cli.RemoteEndPoint); this.cli = cli; buf = new byte[10240]; buflen = 0; cli.BeginReceive(buf, buflen, buf.Length - buflen, SocketFlags.None, new AsyncCallback(GotData), srv); } public void GotData(IAsyncResult res) { int n = cli.EndReceive(res); Console.WriteLine("Read " + n + " bytes from " + cli.RemoteEndPoint); if(n > 0) { buflen += n; int lf = Array.IndexOf(buf, (byte)'\n', 0, buflen); if(lf >= 0) { lf++; ((AServer)res.AsyncState).SendAll(buf, lf, this); if(buflen > lf) { Array.Copy(buf, lf, buf, 0, buflen - lf); } buflen -= lf; } cli.BeginReceive(buf, buflen, buf.Length - buflen, SocketFlags.None, new AsyncCallback(GotData), (AServer)res.AsyncState); } else { Console.WriteLine("Connection closed from " + cli.RemoteEndPoint); ((AServer)res.AsyncState).Remove(this); } } public void Send(byte[] buf, int buflen) { Console.WriteLine("Write " + buflen + " bytes to " + cli.RemoteEndPoint); cli.Send(buf, buflen, SocketFlags.None); } } public class AServer { private List cli; private Socket srv; public AServer(int port) { cli = new List(); srv = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); srv.Bind(new IPEndPoint(IPAddress.Any, port)); srv.Listen(10); srv.BeginAccept(new AsyncCallback(GotConnection), srv); } public void GotConnection(IAsyncResult res) { cli.Add(new AClient(srv.EndAccept(res), this)); srv.BeginAccept(new AsyncCallback(GotConnection), srv); } public void Remove(AClient acli) { cli.Remove(acli); } public void SendAll(byte[] buf, int buflen, AClient me) { Console.WriteLine("Write " + buflen + " bytes to all"); foreach(AClient acli in cli) { if(me != acli) { acli.Send(buf, buflen); } } } public void Close() { srv.Close(); } } public class Program { public static void Main(string[] args) { AServer server = new AServer(1234); Console.ReadKey(); server.Close(); } } }