private bool TryFindProxySession(AcceptedTcpClient acceptedTcpClient, out ProxySession proxySession) { lock (allProxySessions) { proxySession = allProxySessions.FirstOrDefault(p => p.SourceClient.RemoteEndPoint == acceptedTcpClient.RemoteEndPoint); } return(proxySession != null); }
private void ReceiveFromTcpClient(AcceptedTcpClient tcpClient) { CancellationToken cancelReceiveToken; lock (isStartedLock) { if (!isStarted) { return; } cancelReceiveToken = cancelReceiveTokenSource.Token; } ConsumeReceivedBytes(tcpClient, cancelReceiveToken); }
private ProxySession GetOrCreateProxySession(AcceptedTcpClient acceptedTcpClient) { ProxySession proxySession; if (!TryFindProxySession(acceptedTcpClient, out proxySession)) { var rule = configuration.FindRule(acceptedTcpClient.RemoteEndPoint.Address); // TODO: find a better way to do that so it does not block the server from receiving data. var destinationClient = new DataStreamingClient(rule.Destination); destinationClient.ConnectAsync().Wait(); proxySession = new ProxySession(acceptedTcpClient, destinationClient); allProxySessions.Add(proxySession); } return(proxySession); }
private void ConsumeReceivedBytes(AcceptedTcpClient tcpClient, CancellationToken cancelReceiveToken) { bool isConnected = true; var buffer = new byte[1024]; while (isConnected && !cancelReceiveToken.IsCancellationRequested) { int bytesReceived = tcpClient.Receive(buffer); if (bytesReceived > 0) { var localBuffer = new byte[bytesReceived]; Array.Copy(buffer, localBuffer, bytesReceived); DataReceived?.Invoke(tcpClient, new DataReceivedEventArgs(localBuffer)); } else { isConnected = false; } } }
private void ForwardDataToDestination(AcceptedTcpClient acceptedTcpClient, byte[] data) { var proxySession = GetOrCreateProxySession(acceptedTcpClient); proxySession.DestinationClient.Send(data); }
public ProxySession(AcceptedTcpClient sourceClient, DataStreamingClient destinationClient) { SourceClient = sourceClient; DestinationClient = destinationClient; DestinationClient.DataReceived += DestinationClient_DataReceived; }