import socket users={} host = '172.22.102.20' port = 9999 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_socket.bind((host,port)) server_socket.listen(1) server_socket.listen(1) print('等待连接...') client_socket,client_address=server_socket.accept() print(f'已连接:{client_address}') while True: message=client_socket.recv(1024).decode('utf-8') print(f'客户端:{message}') if not message: break if message.startswith('register'): # 处理注册请求 _, username, password = message.split() # 解析用户名和密码 users[username] = password # 保存用户信息 reply_message = f'注册成功,用户名为{username}' elif message.startswith('login'): # 处理登录请求 _, username, password = message.split() # 解析用户名和密码 if users.get(username) == password: # 验证用户身份 reply_message = f'登录成功,欢迎{username}!' else: reply_message = '用户名或密码错误,请重新输入。' reply_message=f'已收到:{message}' client_socket.sendall(reply_message.encode('utf-8')) client_socket.close() client_socket.close()在此基础上增加一个获取客户端列表的功能
时间: 2023-12-21 14:07:30 浏览: 208
tcp_socket.rar_TCP socket_socket_socket tcp_socket-tcp
你可以在 while 循环中增加一个判断,当客户端发送的消息为 "get_client_list" 时,服务器向所有客户端发送一个包含当前连接的客户端列表的消息。以下是示例代码:
```python
import socket
users = {}
connected_clients = set()
host = '172.22.102.20'
port = 9999
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print('等待连接...')
client_socket, client_address = server_socket.accept()
connected_clients.add(client_socket)
print(f'已连接:{client_address}')
while True:
message = client_socket.recv(1024).decode('utf-8')
print(f'客户端:{message}')
if not message:
break
if message.startswith('register'):
_, username, password = message.split()
users[username] = password
reply_message = f'注册成功,用户名为{username}'
elif message.startswith('login'):
_, username, password = message.split()
if users.get(username) == password:
reply_message = f'登录成功,欢迎{username}!'
else:
reply_message = '用户名或密码错误,请重新输入。'
elif message == 'get_client_list':
reply_message = '当前连接的客户端列表:\n'
for client in connected_clients:
reply_message += f'{client.getpeername()[0]}:{client.getpeername()[1]}\n'
else:
reply_message = f'已收到:{message}'
for client in connected_clients:
client.sendall(reply_message.encode('utf-8'))
client_socket.close()
server_socket.close()
```
注意,为了支持多客户端连接,我们需要使用一个集合(set)来保存所有连接的客户端。在客户端连接时,我们将其加入这个集合中。在消息循环中,我们需要向所有客户端发送消息,而不只是当前连接的客户端。
阅读全文