简体   繁体   中英

How to count connected clients in TCPServer?

I'm using Pythons SocketServer.ThreadingTCPServer. Now I want to know how many clients are connected at a certain moment.

How to solve this?

SocketServer.ThreadingTCPServer swap a new thread for each client connection so knowing the number of client connected in a certain moment is the same as knowing how many thread are alive in that moment , so just use threading.activeCount and the number of client will be:

num_client = threading.activeCount() - 1 # Don't count the main thread.

Of course this will not give you correct result if there is other part of your code that swap thread too, so to fix that you can overwrite the process_request() and process_request_thread() methods by adding a counter for clients.

From the example here i wrote this snippet of code to test the two methods

import time
import socket
import threading
from SocketServer import ThreadingTCPServer, BaseRequestHandler


def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    sock.send(message)
    response = sock.recv(1024)
    sock.close()


class ThreadedTCPRequestHandler(BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        cur_thread = threading.currentThread()
        response = "%s: %s" % (cur_thread.getName(), data)
        self.request.send(response)
        time.sleep(1)


class MyServer(ThreadingTCPServer):

    def __init__(self, *args, **kws):
        self._num_client = 0
        ThreadingTCPServer.__init__(self, *args, **kws)

    def process_request(self, *args, **kws):
        print "swap thread"
        self._num_client += 1
        ThreadingTCPServer.process_request(self, *args, **kws)

    def process_request_thread(self, *args, **kws):
        ThreadingTCPServer.process_request_thread(self, *args, **kws)
        print "kill thread"
        self._num_client -= 1

    def get_client_number(self):
        return self._num_client


def my_client_count(ignore=1):
    return  threading.activeCount() - ignore


if __name__ == '__main__':
    server = MyServer(("localhost", 0), ThreadedTCPRequestHandler)

    server_thread = threading.Thread(target=server.serve_forever)
    ip, port = server.server_address

    server_thread.setDaemon(True)
    server_thread.start()

    print "client 1 connected"
    client(ip, port, "Hello World 1")
    print "number of client get_client_number : %s,  enumerate : %s" \
       %  (server.get_client_number(), my_client_count())
    print "client 2 connected"
    client(ip, port, "Hello World 2")
    print "number of client get_client_number : %s,  enumerate : %s" \
       %  (server.get_client_number(), my_client_count())

    time.sleep(3)
    print "client 3 connected"
    client(ip, port, "Hello World 3")
    print "number of client get_client_number : %s,  enumerate : %s" \
       %  (server.get_client_number(), my_client_count())

Output :

client 1 connected
swap client thread
number of client get_client_number : 1,  enumerate : 2
client 2 connected
swap client thread
number of client get_client_number : 2,  enumerate : 3
kill client thread
kill client thread
client 3 connected
swap client thread
number of client get_client_number : 1,  enumerate : 2

Well as you can see the second way give more precise value, and the difference between the two ways is that because my server is running using a thread so i have always +1 thread that explain the difference of 1.

Well hope this can help :)

In a thread that "serves" client use some global count that is increased when client connects and decreased when disconnects.

If you want to count from OS level then use nestat -an with proper grep filter and wc -l (on Windows uses ports of grep and wc )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM