[Edit]
+
0
-
0
C# example client socket class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114// Program.cs file: using System; using System.Text; public class Program { public static void Main() { string host = "some-domain.com"; int port = 80; using (ClientSocket clientSocket = new ClientSocket(host, port)) { // request: byte[] requestBytes = new byte[] {1, 2, 3, /* ... */}; clientSocket.Send(requestBytes); // response: byte[] responseBuffer = new byte[1024]; int responseSize = clientSocket.Receive(responseBuffer); // ... // cleaning: clientSocket.Close(); } } } // ClientSocket.cs file: using System; using System.Net; using System.Net.Sockets; public class ClientSocket: IDisposable { private bool disposed; private Socket socket; public ClientSocket(string host, int port) { IPHostEntry entry = Dns.GetHostEntry(host); this.socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try { this.socket.Connect(entry.AddressList, port); } catch (SocketException ex) { this.socket.Dispose(); throw ex; } } ~ClientSocket() { this.Dispose(false); } public int Send(byte[] buffer) { return this.socket.Send(buffer, SocketFlags.None); } public int Send(byte[] buffer, int offset, int size) { return this.socket.Send(buffer, offset, size, SocketFlags.None); } public int Receive(byte[] buffer) { return this.socket.Receive(buffer, SocketFlags.None); } public int Receive(byte[] buffer, int offset, int size) { return this.socket.Receive(buffer, offset, size, SocketFlags.None); } public void Close() { this.socket.Shutdown(SocketShutdown.Both); this.socket.Close(); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) this.socket.Dispose(); this.disposed= true; } } public void Dispose() { this.Dispose(disposing: true); GC.SuppressFinalize(this); } }