I would like accept incoming TCP Connections as fast as I can. Yet I would also like to have an extra thread for each connection that receives the data.
Here is my TThread Class that listenes to a port:
procedure TListenThread.Execute;
var
iSize : Integer;
begin
ConnectionAttempts := 0;
while not (terminated) do begin
iSize := SizeOf(cAddr);
hClient := Accept(hServer, @cAddr, @iSize);
if (hClient <> INVALID_SOCKET) then begin
inc (ConnectionAttempts);
SynchIP := inet_ntoa(cAddr.sin_addr);
Synchronize(WriteToLog); // Processes very fast!
with TReceiveThread.Create(TRUE) do begin // This takes the longest...
FreeOnTerminate := TRUE;
hSocket := hClient;
TheForm := aForm;
Host := SynchIP;
Resume;
end;
end;
end;
end;
I see that the API CreateThread
takes quite a while to process.
Is there a way to accept connections faster (So the accept
has a higher priority than the ListenerThread)?
For example accept
has the highest priority for 2 seconds (in the 2 seconds the server has accpeted about 200 connections) then create the (200) threads at once, or something like that.
Advise, Help would be appreciated.
PS.: I do NOT want to create any Threads BEFORE a connection occurs. (This would limit the connections and would fill the memory). I would also like to stay away from Indy - I've already tested it and it seems to be the same speed.
What's wrong with Indy? It ships with Delphi, and its TIdTCPServer
component does everything you are asking for. It accepts new connections using a separate worker thread per listening port, so the main thread is not waiting. Each accepted client runs in its own worker thread. And client threads can optionally be pooled (despite what you think, a pool does not have to limit how many connections you can accept, just how many threads are allowed to sit idle at any given moment waiting to be reused).
If you are having speed issues with it, feel free to report it to Indy's developers. I suspect your speed issues are likely to be related to how you are using it, rather than being issues with it itself.