-
-
Save altmind/45c6a0f5965de22d69370d3aaf76adee to your computer and use it in GitHub Desktop.
Asynchronous TCP proxy in C#
This file contains 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.Collections.Generic; | |
using System.Linq; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace HolePunchTest | |
{ | |
public class TcpProxy | |
{ | |
public TcpClient Client { get; set; } | |
public TcpClient HolepunchClient { get; private set; } | |
public TcpProxy(TcpClient client) | |
{ | |
Client = client; | |
HolepunchClient = new TcpClient(); | |
} | |
public async Task DoDataExchange(string address, int port) | |
{ | |
await HolepunchClient.ConnectAsync(address, port); | |
Task T1 = Task.Factory.StartNew(async () => { await DataExchangeTask(Client, HolepunchClient); }); | |
Task T2 = Task.Factory.StartNew(async () => { await DataExchangeTask(HolepunchClient, Client); }); | |
} | |
async Task DataExchangeTask(TcpClient target, TcpClient destination) | |
{ | |
int bytesRead = 0; | |
byte[] recvbuf = new byte[8192]; | |
do | |
{ | |
bytesRead = await target.GetStream().ReadAsync(recvbuf, 0, recvbuf.Length); | |
await destination.GetStream().WriteAsync(recvbuf, 0, bytesRead); | |
} while (bytesRead != 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment