This is the fourteenth part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows
We built a very nice TCP over file System solution. Let’s now implement something similar, based on named pipes. Here comes the code:
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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
using System; using System.Collections.Generic; using System.IO.Pipes; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; namespace PipeProxy { class Program { static void Main(string[] args) { if (args.Length < 2) { Exit(Usage()); } if (args[0] == "client") { Client.Start(args); } else if (args[0] == "pipe_server") { PipeServer.Start(args); } else { Exit(Usage()); } } private static string Usage() { return "PipeProxy.exe client local_port pipe_name\nPipeProxy.exe pipe_server destination_ip:destination_port pipe_name\nPipeProxy.exe port_server destination_ip:destination_port por_name"; } private static void Exit(string message) { Console.WriteLine(message); Environment.Exit(0); } } public class Client { private static Random random = new Random(); public static void Start(string[] args) { var localPort = int.Parse(args[1]); var pipeName = args[2]; Console.WriteLine($"Routing from {localPort} via {pipeName}"); IPEndPoint localEndPoint = new IPEndPoint(0, localPort); Socket listener = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listener.Bind(localEndPoint); listener.Listen(100); var totalSent = new Dictionary<string, long>(); var totalReceived = new Dictionary<string, long>(); var totalExceptions = new Dictionary<string, long>(); var localDnss = new[] {"localhost"}; foreach (var localDns in localDnss) { totalSent[localDns] = 0; totalReceived[localDns] = 0; totalExceptions[localDns] = 0; } new Thread(() => { while (true) { Console.Write(DateTime.Now); Console.Write(" E/S/R:\t"); Console.WriteLine(string.Join("\t", localDnss.Select(dns => $"{dns}: {totalExceptions[dns]}/{totalSent[dns]}/{totalReceived[dns]}"))); Thread.Sleep(3000); } }).Start(); while (true) { try { while (true) { Socket socket = listener.Accept(); Console.WriteLine("New connection accepted to be scattered"); new Thread(() => Start(socket, localDnss, pipeName, random.Next(), totalSent, totalReceived, totalExceptions)).Start(); } } catch (Exception e) { Console.WriteLine("Exception " + e); } } } private static void Start(Socket clientSocket, string[] localDnss, string pipeName, int identifier, Dictionary<string, long> sent, Dictionary<string, long> received, Dictionary<string, long> exceptions) { try { Console.WriteLine("Connecting"); var pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); pipeClient.Connect(); Console.WriteLine("Connected"); var fileSocket = new PipeSocket(clientSocket, pipeClient, r => received[localDnss[0]]+= r, s => sent[localDnss[0]]+=s); fileSocket.Start(); } catch (Exception e) { Console.WriteLine("Exception " + e); } } } class PipeServer { public static void Start(string[] args) { var destinationIp = args[1].Split(':')[0]; var destinationPort = int.Parse(args[1].Split(':')[1]); var pipeName = args[2]; Console.WriteLine($"Routing to {destinationIp}:{destinationPort} via {pipeName}"); NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); while (true) { try { while (true) { Thread.Sleep(1000); pipeServer.WaitForConnection(); // I'm forcing IPv4 (IPv6 breaks with Cisco AnyConnect) IPEndPoint remoteEP = new IPEndPoint(Dns.GetHostEntry(destinationIp).AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork), destinationPort); Socket senderSocket = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); senderSocket.Connect(remoteEP); Console.WriteLine("Socket connected to {0}", senderSocket.RemoteEndPoint); new Thread(() => { var socket = new PipeSocket(senderSocket, pipeServer, r => { }, s => { }); socket.Start(); }).Start(); } } catch (Exception e) { Console.WriteLine("Exception " + e); if (e.Message.Contains("being closed")) { pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); } } } } } public class PipeSocket { private Socket clientSocket; private Stream pipeSocket; private Action<int> received; private Action<int> sent; public PipeSocket(Socket socket, Stream pipeSocket, Action<int> received, Action<int> sent) { this.clientSocket = socket; this.pipeSocket = pipeSocket; this.received = received; this.sent = sent; } public void Start() { Thread clientThread = new Thread(() => { try { var buffer = new byte[100000]; while (true) { var read = clientSocket.Receive(buffer); if (read == 0) { pipeSocket.Close(); return; } while (true) { try { pipeSocket.Write(buffer, 0, read); sent(read); break; } catch (Exception e2) { Console.WriteLine("Exception when writing to pipe" + e2); } } } } catch (Exception e) { Console.WriteLine("Exception in client thread: " + e); } }); try { Thread senderThread = new Thread(KeepReading); senderThread.Start(); } catch (Exception e) { Console.WriteLine("Exception " + e); } clientThread.Start(); clientThread.Join(); } private void KeepReading() { int totalRead = 0; int toRead = 100024; byte[] bytes = new byte[toRead]; try { while (true) { int howMuchRead = pipeSocket.Read(bytes, 0, toRead); if (howMuchRead == 0) break; totalRead += howMuchRead; received(howMuchRead); clientSocket.Send(bytes, 0, howMuchRead, SocketFlags.None); } } catch (Exception e) { Console.WriteLine("Exception while reading" + e); } } } } |
And now the benchmark:
1 2 3 4 5 6 7 |
Mode: PipeProxy 1 0.687 10 2.024 100 1.998 1000 2.039 10000 2.157 100000 3.131 |
This makes it a little slower than the TCP over file System run locally. However, we can’ run this solution between the host and the guest VM (at least I don’t know how to route named pipes to the VM), but we’ll use this code for something else next time.