0

我想知道這對我越來越瘋狂與此:如何知道連接到服務器的客戶端數量並將連接的客戶端數量返回給用戶?

我怎樣才能做到這些:

1 - 如果服務器終止的客戶也應該終止。您的服務器應允許管理員關閉所有連接(即服務器必須等待用戶終止程序(最好通過菜單界面)

2-爲了瞭解連接的客戶端的數量,您需要識別每個連接客戶端唯一 - 這可以通過使用爲每個客戶端連接唯一分配的pid(將這些存儲在全局列表中)來完成。這些連接可以動態更改(即客戶端可以斷開連接並重新連接),因此您必須在服務器上維護此列表。 這是我的服務器端代碼:

在此先感謝

import _thread 
import socket 
import sys 
from datetime import datetime 



def serveclient(c): 
    global v, nclient, vlock, nclientlock 
    while(True): 
     k=(c.recv(1)).decode('utf-8') 
     if(k==''): 
      break 
     if(k=='D'): 
      today = str(datetime.now().strftime('%Y-%m-%d')) 
      c.send(today.encode('utf-8')) 
     if(k=='T'): 
      tme = str(datetime.now().strftime('%H:%M:%S')) 
      c.send(tme.encode('utf-8')) 
     if(k=='X'): 
        <<<< # Here I should put the number of clients connected and echo back the number like the above code 
     vlock.acquire() 
     v+=k 
     vlock.release() 

     #Echo back 
     c.send(v.encode('utf-8')) 
    c.close() #End connection 
    nclientlock.acquire() 
    nclient-=1 
    nclientlock.release() 

#Main driver code 
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
port = int(sys.argv[1]) 
listener.bind(('',port)) 
listener.listen(5) 

#Initialize global data 
v='' 
vlock=_thread.allocate_lock() 
nclient=10  #Max number of clients 
nclientlock=_thread.allocate_lock() 

#accept calls from clients 
for i in range(nclient): 
    (client, ap) = listener.accept() 
    _thread.start_new_thread(serveclient, (client,)) 

listener.close() 
while nclient >0: 
    pass #do nothing, just wait for client count to drop to zero 

print('The final string is: ', v) 

<<<<<<<<<<<<<<<<<<<<<<<<<This the Client Code>>>>>>>>>>>>>>>>>>>>>>> 

#Client Program. Sends a single char at a time to the server until the client 
    #sends a '', this will terminate the client. 
    # 
    #usage: python server port 

    import socket 
    import sys 

    #create the socket 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    host = sys.argv[1]  #Server info from cmd line 
    port = int(sys.argv[2]) #Port from cmd line 

    #Conncet to server 
    s.connect((host, port)) 

    while(True): 
     #get letter 
     k = input('enter a letter: ') 
     s.send(k.encode('utf-8')) 
     if(k==''): 
      break 
     v=s.recv(1024) #receive upto 1024 bytes 
     print(v.decode('utf-8')) 

    s.close() 

回答

0

只是每次你接受一個插座,並在每次關閉一個公認的插座時減小它的時候增加一個計數。