2016-12-13 6 views
3

私がダウン に行くために私のpython靴下・サーバーの接続カウンタを作成しようとしてきたが、私は、私はこのは、どのように私は私の接続カウンタがダウンして行くことができます

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

Iを行うことができますどのように把握することはできませんこんにちはこの問題とは無関係なので、すべてのコードを表示する必要はありません。 新しい接続が接続されたときにカウンタを作成するコードを提供しましたが、前にも述べたように、接続が離れる。

オンラインがここに私の問題

+0

スレッド数が有効ですか? – Fejs

+0

@Fejsカウンタを上げるためにスレッドを使用していないのは、クライアント= 0クライアント=クライアント+ 1を使用していますが、カウンタが接続を検出してから接続を終了するように変更する必要があります – Capricorn

+0

悪い。クライアントごとにスレッドを作成したくない*ではありません。ちょうどあなたのコードの頭を上げてください。 – Bauss

答えて

0

を助けることができるショーの何も解決策を見つけることを試みるselect.select機能を使用して、クライアントのカウンタを実現するためにどのように小さなサンプルです。私は実際にselect – Wait for I/O Efficientlypymotw.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) 
関連する問題