PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] How to set max number of connections in SocketServer

 October 22, 2022     python, python-2.7, sockets, socketserver     No comments   

Issue

I'm trying to find a way how to set a limit - maximum number of connections in SocketServer.

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    daemon_threads = True


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        some code 

Is there some way how to do that? For example maximum 3 clients.


Solution

The simplest solution is to count active connections and simply stop serving new connections when the limit is reached. The downsize is that the new TCP connections are accepted and then closed. Hope that's OK.

The code I'm using in a server NOT based on a SocketServer looks basically like this:

A variable is needed:

accepted_sockets = weakref.WeakSet()

The WeakSet has the advantage that no longer used elements get deleted automatically.

A trivial helper function:

def count_connections():
     return sum(1 for sock in accepted_sockets if sock.fileno() >= 0)

And the usage in the request handling code is straightforward:

   if count_connections() >= MAX_CONN:
        _logger.warning("Too many simultaneous connections")
        sock.close()
        return
    accepted_sockets.add(sock)
    # handle the request

You have to adapt it for use with SocketServer (e.g. the TCP socket is called request there, probably the server handles the socket.close, etc.), but hope it helps.



Answered By - VPfB
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing