Skip to content

Instantly share code, notes, and snippets.

@altmind
Forked from Mordo95/TcpProxy.cs
Created November 17, 2022 21:50
Show Gist options
  • Save altmind/247615821aa8341a18a761dbe17392dd to your computer and use it in GitHub Desktop.
Save altmind/247615821aa8341a18a761dbe17392dd to your computer and use it in GitHub Desktop.
Asynchronous TCP proxy in C#
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