我正在python中构建一个与客户端一起工作的tcp / ip服务器。 每个客户端都有自己的线程,其套接字被添加到名为client_list的列表中。 还有一个变量“clients_connected”,用于存储连接的客户端数量。 由于某种原因,它目前只与一个客户合作。 此外,当客户端断开连接时,它应该从client_list中删除,但我不知道如何做到这一点。 你能看一下代码吗?非常感谢!
此线程正在寻找传入连接:
def addclientsthread(sock):
global client_list
conn, addr = sock.accept()
client_list += [conn]
print_line('Client connected on ' + addr[0] + "\n")
start_new_thread(clientthread, (conn,))
因此,当客户端连接时,它会获得自己的“clientthread”
def clientthread(conn):
# handling connections.
global clients_connected
while True:
# Receiving from client
in_data = conn.recv(1024)
data = decrypt(in_data)
if data.lower().find("id=-1") != -1:
clients_connected += 1
print_line("new client ID set to " + str(clients_connected) + "\n")
crypted_msg = encrypt("SID=" + str(clients_connected))
conn.sendall(crypted_msg)
pass
elif data.lower().find("uin") == 0:
uin_id = int(data[4:])
clients_connected -= 1
break
else:
print_line(data)
if not data:
break
# If client disconnects
conn.close()
哦,请不要讨厌,我刚刚开始编码:)
编辑:这是主要代码(不在线程中)
HOST = ''
PORT = 8820
clients_connected = 0
client_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
# Bind socket to host and port
try:
s.bind((HOST, PORT))
except socket.error, msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket successfully binded'
# Start listening on socket
s.listen(100000)
print 'Socket is listening'
start_new_thread(addclientsthread, (s,))