// 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.IO; using System.Net; using System.Net.Sockets; using System.Text; namespace SocketDemo.Binary.High.SingleServer { public class Program { private static int HTON(int v) { if(BitConverter.IsLittleEndian) { byte[] buf = BitConverter.GetBytes(v); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else { return v; } } private static int NTOH(int v) { if(BitConverter.IsLittleEndian) { byte[] buf = BitConverter.GetBytes(v); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else { return v; } } private const int PORT = 12345; private const int BACKLOG = 100; public static void Main(string[] args) { // listen on port TcpListener srv = new TcpListener(IPAddress.Any, PORT); srv.Start(BACKLOG); while(true) { // accept connection TcpClient cli = srv.AcceptTcpClient(); // get reader and writer NetworkStream stm = cli.GetStream(); BinaryReader br = new BinaryReader(stm); BinaryWriter bw = new BinaryWriter(stm); Console.WriteLine("(connection from {0})", cli.Client.RemoteEndPoint); // read a and b int a = NTOH(br.ReadInt32()); int b = NTOH(br.ReadInt32()); // calculate c and send int c = a + b; bw.Write(HTON(c)); bw.Flush(); // read v int buflen = br.ReadByte(); byte[] buf = new byte[buflen]; int ix = 0; while(ix < buf.Length) { ix += br.Read(buf, ix, buf.Length - ix); } string v = Encoding.UTF8.GetString(buf); // calculate v2 and send string v2 = v + v; byte[] v2b = Encoding.UTF8.GetBytes(v2); bw.Write((byte)v2b.Length); bw.Write(v2b); bw.Flush(); // close connection br.Close(); bw.Close(); cli.Close(); } } } }