// 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; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; class ChatMain { public static void Main(string[] args) { Server srv = new Server(); srv.Run(); } } class Server { private ArrayList allclients; public void Run() { allclients = new ArrayList(); TcpListener server = new TcpListener(IPAddress.Any, 50000); server.Start(); while(true) { TcpClient client = server.AcceptTcpClient(); ClientHandler ch = new ClientHandler(client, this); allclients.Add(ch); (new Thread(new ThreadStart(ch.Run))).Start(); } } public void SendAll(string msg) { foreach(ClientHandler ch in allclients) { ch.Send(msg); } } public void Remove(ClientHandler ch) { allclients.Remove(ch); } } class ClientHandler { private StreamReader rdr; private StreamWriter wrt; private Server srv; public ClientHandler(TcpClient cli, Server srv) { rdr = new StreamReader(cli.GetStream()); wrt = new StreamWriter(cli.GetStream()); this.srv = srv; } public void Run() { while(true) { string line = rdr.ReadLine(); string cmd = line.Split(" ".ToCharArray())[0]; if(cmd == "SEND") { srv.SendAll(line.Substring(5)); } else if(cmd == "EXIT") { srv.Remove(this); return; } } } public void Send(string msg) { lock(wrt) { wrt.WriteLine(msg); wrt.Flush(); } } }