// 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.Text; using System.Net.Sockets; 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 ClientBinary { private const byte ADD = 1; private const byte DUP = 2; private const byte RES = 3; public static void Main(string[] args) { // connect til server TcpClient cli = new TcpClient("localhost", 12345); BinaryWriter bw = new BinaryWriter(cli.GetStream()); BinaryReader br = new BinaryReader(cli.GetStream()); byte res; // skriv til server int a = 12; int b = 34; bw.Write(ADD); bw.Write(EndianUtil.Swap(a)); bw.Write(EndianUtil.Swap(b)); bw.Flush(); // læs fra server og skriv resultat til skærm res = br.ReadByte(); int c = EndianUtil.Swap(br.ReadInt32()); Console.WriteLine(c); // skriv til server string s = "abc"; byte[] data = Encoding.Default.GetBytes(s); bw.Write(DUP); bw.Write(EndianUtil.Swap((short)data.Length)); bw.Write(data); bw.Flush(); // læs fra server og skriv resultat til skærm res = br.ReadByte(); int len = EndianUtil.Swap(br.ReadInt16()); byte[] data2 = new byte[len]; int ix = 0; while(ix < len) { ix += br.Read(data2, ix, len - ix); } string s2 = Encoding.Default.GetString(data2); Console.WriteLine(s2); // disconnect cli.Close(); } }