Vladimir Kruglov Vladimir Kruglov - 1 month ago 16
C# Question

Proxy server using socket

i'm writing proxy server and using for it sockets, the problem here is how to detect end of data and close socket, or understand how browser is doing it.
my proxy is very simple, it just forwards requests using certain network adapter to intranet proxy, so there is no request parsing and ssl do not require extra authentication

public void Start(IPEndPoint local, IPEndPoint remote)
{
_mainSocket.Bind(local);
_mainSocket.Listen(100);


while (true)
{
var source = _mainSocket.Accept();
var destination = new TcpForwarder();
var state = new State(source, destination._mainSocket, localSockets);

destination._mainSocket.Bind(new IPEndPoint(IPAddress.Parse("10.94.136.231"), 0));
destination.Connect(remote, source);
source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}

private void Connect(EndPoint remoteEndpoint, Socket destination)
{
var state = new State(_mainSocket, destination, local, destinationstate);

_mainSocket.Connect(remoteEndpoint);
_mainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
}


OnDataReceive
just read everything send to another socket and continue listening

but for every request there is made another socket connection, and i don't know when i can close it, even if i close browser both sockets still have Connected status, and they stay forever, as this proxy is local i can restart everything when it fails but, still i want to understand how requests work, isn't tcpip request same as open socket and send certain headers?

Answer

looks like if i close socket if there was no data received then it's enough, browser receives everything it requires and there is no leak, so i assume it's correct way

var bytesTransferred = state.SourceSocket.EndReceive(readSocket);
if (bytesTransferred == 0)
{
    state.SourceSocket.Close();
    state.DestinationSocket.Close();
}