我怎样才能使我的连接计数器关闭

2024-04-25 18:03:43 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我一直在努力使我的pythonsock服务器连接计数器下降 但我想不出我该怎么做

def client_thread(conn):
    while True:
        conn.send("Command: ")
        data = conn.recv(1024)
        if not data:
            break
        reply = "" + data
        conn.sendall("\r")
        if data == "!* Connections":
            conn.sendall("[+] Clients Connected: %s \r\n" % (clients))
    conn.close()

while True:
    conn, addr = sock.accept()

    clients = clients + 1

    start_new_thread(client_thread, (conn,))

sock.close()

我不需要把所有的代码都给你看,因为它和这个问题无关, 我提供了一个代码,当一个新连接连接时,计数器会上升,但正如前面所说,我不知道如何在连接离开时使计数器下降。你知道吗

当试图在网上找到解决方案时,没有什么能帮助我解决问题


Tags: 代码服务器clienttrueclosedataif计数器
1条回答
网友
1楼 · 发布于 2024-04-25 18:03:43

下面是一个如何使用select.select函数实现客户机计数器的小示例。实际上,我从pymotw.com上的伟大文章select – Wait for I/O Efficiently中获取了它,并添加了一个客户机计数器。基本上,您会寻找可读的套接字并尝试从中接收数据。如果套接字不返回任何内容,则表示它已关闭,可以从客户机列表中删除。你知道吗

import queue
import socket
import select

clients = 0

sock = socket.socket()
sock.bind(('localhost', 5000))
sock.listen(5)

inputs = [sock]
outputs = []
msg_queues = {}

while inputs:
    readable, writable, exceptional = select.select(
        inputs, outputs, msg_queues)

    for s in readable:

        if s is sock:
            conn, addr = sock.accept()
            print('new connection from ', addr)
            conn.setblocking(0)
            inputs.append(conn)
            msg_queues[conn] = queue.Queue()

            # increment client counter
            clients += 1
            print('Clients: ', clients)

        else:
            # try to receive some data
            data = s.recv(1024)

            if data:
                # if data available print it
                print('Received {} from {}'.format(data, s.getpeername()))
                msg_queues[s].put(data)

                # add output channel for response
                if s not in outputs:
                    outputs.append(s)
            else:
                # empty data will be interpreted as closed connection
                print('Closing connection to ', s.getpeername())

                # stop listening for input on the connection
                if s in outputs:
                    outputs.remove(s)

                # remove from inputs
                inputs.remove(s)
                s.close()

                # decrement client counter
                clients -= 1

                del msg_queues[s]
                print('Clients: ', clients)

相关问题 更多 >