Assume a listening socket on localhost:80 and a client connecting using: telnet localhost 80
The problem is that I want only to accept a limited number of concurrent clients, assume only one. After that I simply don't accept any.
The problem that I saw using: netstat -a is that next client connection was established. Yes I don't process it, but on a system level it is there shown as ESTABLISHED, client can send data and probably cause extra overhead to the system.
The only way I see is to continue accepting clients but disconnect them. Am I right?
-
If you stop listening on that port it should not be allowing any more incoming connections. Make sure the listener closes after accepting the first connection.
Two other options:
Use Raw Sockets (if you OS supports them). And manually handle the TCP connections. This will involve a lot of extra code and processing though.
Use UDP. They are stateless connections but then you will have to accept/reject packets based on something else. This doesn't have the overhead of a TCP connection though. Also you will not be able to use things like telnet for testing.
Arthur : that would do, but it will hit performance because we will start/stop listening each time when number of concurrent clients pass the threshold. -
The
listen()function has abacklogparameter that specifies how many outstanding sockets are allowed to hang around in the operating system kernel waiting for the server toaccept()them.On my Linux system the man page for
listen()says that most of the time the client will get aconnection refusederror - just the same as if the socket wasn't listening at all.If you only ever want to handle one connection, that's fine, you can just do:
listen(s, 0); while ((new_fd = accept(s)) >= 0) { process(new_fd); }It would be somewhat harder if you want to handle more than one. You can't just set the
backlogparameter to the number of concurrent connections, since the parameter doesn't take into account how many connections are already active. -
You should simply close the listening socket when you no longer wish to accept more connections and open it again when you do wish to accept connections. The listen backlog wont help you at all as it's simply for 'half open' connections that the TCP/IP stack has accepted but that the application program hasn't yet accepted.
0 comments:
Post a Comment