Created
June 6, 2021 11:53
-
-
Save Pan-Maciek/a9c250740f7bdeddcae761fbdaca4352 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Threading.Tasks; | |
const int grpcPort = 5000; | |
const int proxyPort = 3000; | |
var tcp1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
tcp1.Bind(new IPEndPoint(IPAddress.Loopback, proxyPort)); | |
tcp1.Listen(); | |
var pipe = true; | |
Task.Factory.StartNew(() => { | |
while (true) { | |
var source = tcp1.Accept(); | |
var target = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
target.Connect(new IPEndPoint(IPAddress.Loopback, grpcPort)); | |
var sourceStream = new NetworkStream(source); | |
var targetStream = new NetworkStream(target); | |
Task.Factory.StartNew(() => { | |
var buffer = new byte[1024]; | |
while (true) { | |
var read = sourceStream.Read(buffer); | |
if (pipe) { | |
targetStream.Write(buffer, 0, read); | |
} | |
} | |
}); | |
Task.Factory.StartNew(() => { | |
var buffer = new byte[1024]; | |
while (true) { | |
var read = targetStream.Read(buffer); | |
if (pipe) { | |
sourceStream.Write(buffer, 0, read); | |
} | |
} | |
}); | |
} | |
}); | |
while (true) { | |
Console.CursorLeft = 0; | |
Console.Write("TCP proxy " + (pipe ? "on" : "off") + ". Press any key to toggle. "); | |
Console.ReadKey(true); | |
pipe = !pipe; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment