如何统计TCPServer中连接的客户端数量?

发布于 2024-10-24 17:50:29 字数 91 浏览 2 评论 0 原文

我正在使用Pythons SocketServer.ThreadingTCPServer。现在我想知道在某个时刻有多少客户端连接。

怎么解决这个问题呢?

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

How to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

堇年纸鸢 2024-10-31 17:50:29

SocketServer.ThreadingTCPServer 为每个客户端连接交换一个新线程,因此了解某一时刻连接的客户端数量与了解该时刻有多少线程处于活动状态相同,因此只需使用 threading.activeCount 和客户端的数量将是:

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

当然,如果有其他部分,这不会给你正确的结果你的交换线程的代码同样,为了解决这个问题,您可以通过为客户端添加计数器来覆盖 process_request() 和 process_request_thread() 方法。

从示例此处我编写了这段代码来测试这两种方法

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())

输出:

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

以及你可以看到第二种方法给出了更精确的值,两种方法之间的区别在于,因为我的服务器正在使用线程运行,所以我总是+1线程来解释1的区别。

希望这可以有所帮助:)

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 :)

单挑你×的.吻 2024-10-31 17:50:29

在“服务”客户端的线程中,使用一些全局计数,该计数在客户端连接时增加,在断开连接时减少。

如果您想从操作系统级别进行计数,请使用 nestat -an 以及适当的 grep 过滤器和 wc -l (在 Windows 上使用 >grepwc

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文