如何知道连接到服务器的客户端数量并将连接的客户端数量返回给用户?

时间:2013-12-16 21:27:59

标签: python multithreading sockets network-programming client-server

我想知道这些因为我对此感到疯狂:

我该怎么做:

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

1 个答案:

答案 0 :(得分:0)

每次接受套接字时,只需递增一个计数,并在每次关闭接受的套接字时递减计数。