Reputation: 1588
I'm trying to make a chat server thing. Basically, I want more than one client to be able to connect at the same time.
I want it so it's always listening. Whenever anyone tries to connect, it instantly accepts them and adds them to a list of connections.
I could have a listen(1) then a timeout, and keep appending them to a list then closing the socket, and making a new one, then listening with a timeout, etc. Although, this seems very slow, and I'm not even sure it would work
Keep in mind, it does not HAVE to be socket. If there is any other kind of network interface, it would work just as well.
Upvotes: 1
Views: 1167
Reputation: 310980
I want it so it's always listening. Whenever anyone tries to connect, it instantly accepts them and adds them to a list of connections.
So you just have:
An accept() loop that does nothing but accept() new connections and start a new thread to handle each one.
A thread per connection that reads with a long timeout, whatever you want your session idle timeout to be. If the timeout expires, you close the socket and exit the thread.
If the server runs out of FDs, which it will if there are enough simultaneous connections, accept() will start failing with a corresponding errno: in this case you just ignore it and keep looping. Maybe you decrease the idle timeout in this situation, and put it back when accepts start to work again.
Upvotes: 0
Reputation: 1174
Consider whether you actually need to maintain separate sockets for every connection. Would something like connectionless UDP be appropriate? That way you could support an arbitrary number of users while only using one OS socket.
Of course, with this approach you'd need to maintain connection semantics internally (if your application cares about such things); figure out which user each datagram has been sent either by looking at their IP/port or by examining some envelope data within your network protocol, send occasional pings to see whether the other side is still alive, etc. But this approach should nicely separate you from any OS concerns RE: number of sockets your process is allowed to keep open at once.
Upvotes: 2
Reputation: 2885
You are looking at the problem slightly wrong. With server-side sockets, you accept connections to the same socket, which are then handled by other processes/threads.
#
# Setup socket and other handling stuff here
#
while True:
conn = sock.accept()
thread.start_new_thread(handler, (conn,))
Upvotes: 1
Reputation: 11322
There will be a practical limit on the maximum number of sockets based on the memory your system.
See http://docs.python.org/2/library/socketserver.html. I think the last few examples (under Asynchronous Mixins) come very close to what you want to achieve.
Upvotes: 3