// 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.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); } 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); while(true) { // accept connection Socket s = ss.Accept(); Console.WriteLine("(connection from {0})", s.RemoteEndPoint); 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)); // 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(); } } } }