Skip to content

Instantly share code, notes, and snippets.

@Mordo95
Created February 7, 2018 15:10
Show Gist options
  • Save Mordo95/a3f8888379930c641fefbc6db6cc5787 to your computer and use it in GitHub Desktop.
Save Mordo95/a3f8888379930c641fefbc6db6cc5787 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