2

Right now I'm building a server-client program using TCP in Python with the sockets module. Having looked all over the internet, it has become apparent that a conn, addr = server.accept() line is required in the server code, however there is no way for the server to know when the client will connect. It could be from seconds to minutes after the server is run.

So my question is this: can I use threading to constantly run a server.accept() line of code so any client that chooses to connect can? Or could this lead to something malicious connecting?

krizajb
  • 1,715
  • 3
  • 30
  • 43
  • Possible duplicate of [Can 'connect' call on socket return successfully without server calling 'accept'?](https://stackoverflow.com/questions/2409277/can-connect-call-on-socket-return-successfully-without-server-calling-accept) – ivan_pozdeev Oct 18 '18 at 10:12
  • If an answer resolved your problem, please consider [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it. – ivan_pozdeev Dec 05 '18 at 09:30

1 Answers1

1

As per Can 'connect' call on socket return successfully without server calling 'accept'? ,

TCP establishes the connection - the 3-way handshake - under the covers and puts it in a completed connection queue when it is ready. Accept() returns the next waiting connection from the front of this queue.

From the client's perspective it is "connected" but it won't be talking to anyone until the server accepts and begins processing. Sort of like when you call a company and are immediately put in the hold queue. You are "connected" but no business is going to be done until someone actually picks up and starts talking.

So, you won't "miss" connections if you're not doing that. But accept() is typically run in an infinite loop anyway -- in the main thread or otherwise -- 'cuz it's server's primary job to service clients.

According to Is accept() thread-safe? , accept() is thread-safe, you can very well have it running in a separate thread, or even have multiple accept() calls in different threads (or even different processes in OSes with fork) at the same time.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152