I'm trying to do TCP Hole Punching in Delphi. I have only one port opened - 10000 (for testing purposes).
Here is a snippet of my code (full source code):
procedure TFormMain.btnEnableRedirectClick(Sender: TObject);
begin
IdTCPServerRetr.Active:=True;
end;
procedure TFormMain.btnConnectToClientClick(Sender: TObject);
begin
if IdTCPClientRemote.Port = 0 then
ShowMessage('Wait for connection to redirect server...')
else begin
IdTCPClientRemote.Host:=MyIP;
IdTCPClientRemote.Connect;
ShowMessage('S U C C E S S');
end;
end;
procedure TFormMain.btnConnectClick(Sender: TObject);
begin
IdTCPClientLocal.Host:=MyIP;
IdTCPClientLocal.Connect;
ShowMessage('Connected to redirect server!');
end;
procedure TFormMain.btnListenClick(Sender: TObject);
begin
IdTCPServerLocal.DefaultPort:=IdTCPClientLocal.Socket.Binding.Port;
IdTCPServerLocal.Active:=True;
ShowMessage('Local server started!');
end;
procedure TFormMain.IdTCPServerRetrExecute(AContext: TIdContext);
begin
IdTCPClientRemote.Port:=AContext.Connection.Socket.Binding.PeerPort;
end;
First, I run the remote server (for redirection) on port 10000.
IdTCPServerRetr.Active:=True;
After that, I connect to the redirect server (port 10000) and create local server, using the same port as at client.
IdTCPClientLocal.Connect; IdTCPServerLocal.DefaultPort:=IdTCPClientLocal.Socket.Binding.Port; IdTCPServerLocal.Active:=True;
(client and server have a reusesocket = rsTrue)
After that, I try to connect to the client, on its internal port, but I get the error "Connection Timeout".
I think the problem is that the remote client can't find the server to connect, since the client has already established a connection with the redirect server.
Try to set a high value of
TIdTCPClient.ConnectTimeout
, like 5000 or more (miliseconds).