import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('172.26.79.123', 9999)) server_socket.listen(5) clients = {} ##注册 def register(client_socket): # 处理客户端注册请求 # 获取注册信息 username = client_socket.recv(1024).decode() password = client_socket.recv(1024).decode() # 存储注册信息 # 这里可以使用文件、数据库等方式存储信息 # 为简单起见,我们在字典中存储注册信息 if username in clients: client_socket.send(b'Username already exists.') else: clients[username] = password client_socket.send(b'Register success.') ##登陆 def login(client_socket): # 处理客户端登录请求 # 获取登录信息 username = client_socket.recv(1024).decode() password = client_socket.recv(1024).decode() # 验证登录信息 if username in clients and clients[username] == password: client_socket.send(b'Login success.') else: client_socket.send(b'Login failed.') def handle_client(client_socket): # 处理客户端请求 while True: # 获取客户端请求类型 request_type = client_socket.recv(1024).decode() if request_type == 'register': register(client_socket) elif request_type == 'login': login(client_socket) else: client_socket.send(b'Invalid request type.') while True: client_socket, addr = server_socket.accept() clients[client_socket] = addr print('Connected with', addr) handle_client(client_socket)这是服务器端的代码,其中有注册和登陆的功能,请根据此代码写出对应的客户端的代码
时间: 2024-01-02 11:04:32 浏览: 212
以下是客户端代码:
```
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('172.26.79.123', 9999))
def register():
# 处理注册请求
username = input('Please enter your username: ')
password = input('Please enter your password: ')
client_socket.send('register'.encode())
client_socket.send(username.encode())
client_socket.send(password.encode())
response = client_socket.recv(1024).decode()
print(response)
def login():
# 处理登录请求
username = input('Please enter your username: ')
password = input('Please enter your password: ')
client_socket.send('login'.encode())
client_socket.send(username.encode())
client_socket.send(password.encode())
response = client_socket.recv(1024).decode()
print(response)
while True:
action = input('Please enter an action (register/login): ')
if action == 'register':
register()
elif action == 'login':
login()
else:
print('Invalid action.')
```
阅读全文