// 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.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; class EndianUtil { public static short Swap(short v) { return (short)(((v >> 8) & 0x00FF) | ((v << 8) & 0xFF00)); } public static int Swap(int v) { uint v2 = (uint)v; return (int)(((v2 >> 24) & 0x000000FF) | ((v2 >> 8) & 0x0000FF00) | ((v2 << 8) & 0x00FF0000) | ((v2 << 24) & 0xFF000000)); } } class ServerText { public static void Main(string[] args) { // lyt på port 12345 TcpListener srv = new TcpListener(IPAddress.Any, 12345); srv.Start(); while(true) { // accepter connection fra client TcpClient cli = srv.AcceptTcpClient(); // start tråd til at håndtere client BinaryClientHandler bch = new BinaryClientHandler(cli); (new Thread(new ThreadStart(bch.Run))).Start(); } } } class BinaryClientHandler { private const byte ADD = 1; private const byte DUP = 2; private const byte RES = 3; private TcpClient cli; private BinaryReader br; private BinaryWriter bw; public BinaryClientHandler(TcpClient cli) { // initialiser læse og skrive klasser this.cli = cli; br = new BinaryReader(cli.GetStream()); bw = new BinaryWriter(cli.GetStream()); } public void Run() { bool more = true; while(more) { // læs input fra client byte cmd = br.ReadByte(); switch(cmd) { case ADD: // læg to heltal sammen int a = EndianUtil.Swap(br.ReadInt32()); int b = EndianUtil.Swap(br.ReadInt32()); int c = a + b; bw.Write(RES); bw.Write(EndianUtil.Swap(c)); bw.Flush(); break; case DUP: // dupliker en streng int len = EndianUtil.Swap(br.ReadInt16()); byte[] data = new byte[len]; int ix = 0; while(ix < len) { ix += br.Read(data, ix, len - ix); } String s = Encoding.Default.GetString(data); String s2 = s + s; byte[] data2 = Encoding.Default.GetBytes(s2); bw.Write(RES); bw.Write(EndianUtil.Swap((short)data2.Length)); bw.Write(data2); bw.Flush(); break; default: Console.WriteLine("Unknown command: " + cmd); more = false; break; } } // luk læse og skrive klasser br.Close(); bw.Close(); cli.Close(); } }