// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; namespace SocketDemo.Binary.Low.SingleServer { public class Program { private static byte[] IntToBytes(int v) { byte[] buf = BitConverter.GetBytes(v); if(BitConverter.IsLittleEndian) Array.Reverse(buf); return buf; } private static int BytesToInt(byte[] buf) { if(BitConverter.IsLittleEndian) Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } public delegate void EventHandler(Socket s, IList sel, IDictionary h); public static void AcceptHandler(Socket ss, IList sel, IDictionary h) { // accept connection Socket s = ss.Accept(); Console.WriteLine("(connection from {0})", s.RemoteEndPoint); // next handler sel.Add(s); h[s] = ReceiveIntegerHandler; } public static void ReceiveIntegerHandler(Socket s, IList sel, IDictionary h) { byte[] buf; int ix; // read a and b buf = new Byte[4]; ix = 0; while(ix < buf.Length) { ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None); } int a = BytesToInt(buf); buf = new Byte[4]; ix = 0; while(ix < buf.Length) { ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None); } int b = BytesToInt(buf); // calculate c and send int c = a + b; s.Send(IntToBytes(c)); // next handler h[s] = ReceiveStringHandler; } public static void ReceiveStringHandler(Socket s, IList sel, IDictionary h) { byte[] buf; int ix; // read v buf = new Byte[1]; s.Receive(buf); int buflen = buf[0]; buf = new byte[buflen]; ix = 0; while(ix < buf.Length) { ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None); } string v = Encoding.UTF8.GetString(buf); // calculate v2 and send string v2 = v + v; byte[] v2b = Encoding.UTF8.GetBytes(v2); s.Send(new byte[] { (byte)v2b.Length }); s.Send(v2b); // close connection s.Close(); // next handler sel.Remove(s); h.Remove(s); } private const int PORT = 12345; private const int BACKLOG = 100; public static void Main(string[] args) { // listen on port Socket ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ss.Bind(new IPEndPoint(IPAddress.Any, PORT)); ss.Listen(BACKLOG); IList sel = new ArrayList(); IDictionary h = new Dictionary(); sel.Add(ss); h.Add(ss, AcceptHandler); while(true) { // select IList sav = new ArrayList(sel); Socket.Select(sel, null, null, 1000000); foreach(Socket s in sel) { h[s](s, sav, h); } sel = sav; } } } }