// 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.Sockets; using System.Text; namespace SocketDemo.Binary.Low.Client { 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 string HOST = "localhost"; private const int PORT = 12345; public static void Main(string[] args) { // open connection Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(HOST, PORT); Console.WriteLine("(connected)"); byte[] buf; int ix; // send a and b int a = 123; int b = 456; s.Send(IntToBytes(a)); s.Send(IntToBytes(b)); // receive c and print buf = new Byte[4]; ix = 0; while(ix < buf.Length) { ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None); } int c = BytesToInt(buf); Console.WriteLine(c); // send v string v = "ABC"; byte[] vb = Encoding.UTF8.GetBytes(v); s.Send(new byte[] { (byte)vb.Length }); s.Send(vb); // receive v2 and print 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 v2 = Encoding.UTF8.GetString(buf); Console.WriteLine(v2); // close connection s.Close(); } } }