如何让我的连接计数器停止运行

时间:2016-12-13 09:14:09

标签: python sockets

您好我一直在尝试让我的python sock服务器连接计数器停止运行 但我无法弄清楚我该怎么做

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

我无需向您展示所有代码,因为它与此问题无关, 我已经提供了一个代码,当新的连接连接时,它会使计数器上升,但如前所述,我不知道如何在连接离开时将其关闭。

在尝试在线查找解决方案时,显示的任何内容都无法解决我的问题

1 个答案:

答案 0 :(得分:1)

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

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)