基于select模式启动服务器,然后启动两个客户端 A 和 B,客户端 A 发消息给服务器,服务器转发给客户端 B ,客户端B打印显示接收到的消息。客户端B发消息给服务器,服务器转发给客户端A,客户端A打印显示接收到的消息。
时间: 2024-06-12 12:06:32 浏览: 66
以下是基于select模式实现的服务器和客户端代码:
服务器代码:
```python
import socket
import select
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('localhost', 8888))
server_socket.listen(5)
sockets_list = [server_socket]
clients = {}
print('Server started and listening on port 8888')
def receive_message(client_socket):
try:
message_header = client_socket.recv(1024)
if not len(message_header):
return False
message_length = int(message_header.decode('utf-8').strip())
return {'header': message_header, 'data': client_socket.recv(message_length)}
except:
return False
while True:
read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)
for notified_socket in read_sockets:
if notified_socket == server_socket:
client_socket, client_address = server_socket.accept()
user = receive_message(client_socket)
if user is False:
continue
sockets_list.append(client_socket)
clients[client_socket] = user
print(f'Accepted new connection from {client_address[0]}:{client_address[1]} '
f'username:{user["data"].decode("utf-8")}')
else:
message = receive_message(notified_socket)
if message is False:
print(f'Closed connection from {clients[notified_socket]["data"].decode("utf-8")}')
sockets_list.remove(notified_socket)
del clients[notified_socket]
continue
user = clients[notified_socket]
print(f'Received message from {user["data"].decode("utf-8")}: {message["data"].decode("utf-8")}')
for client_socket in clients:
if client_socket != notified_socket:
client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
del clients[notified_socket]
```
客户端A代码:
```python
import socket
import sys
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8888))
username = input('Enter your username: ')
client_socket.send(bytes(username, 'utf-8'))
while True:
message = input(f'{username} > ')
if message:
message = bytes(message, 'utf-8')
message_header = f'{len(message):<10}'.encode('utf-8')
client_socket.send(message_header + message)
try:
while True:
username_header = client_socket.recv(10)
if not len(username_header):
print('Connection closed by the server')
sys.exit()
username_length = int(username_header.decode('utf-8').strip())
username = client_socket.recv(username_length).decode('utf-8')
message_header = client_socket.recv(10)
message_length = int(message_header.decode('utf-8').strip())
message = client_socket.recv(message_length).decode('utf-8')
print(f'{username} > {message}')
except:
continue
```
客户端B代码:
```python
import socket
import sys
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8888))
username = input('Enter your username: ')
client_socket.send(bytes(username, 'utf-8'))
while True:
try:
while True:
username_header = client_socket.recv(10)
if not len(username_header):
print('Connection closed by the server')
sys.exit()
username_length = int(username_header.decode('utf-8').strip())
username = client_socket.recv(username_length).decode('utf-8')
message_header = client_socket.recv(10)
message_length = int(message_header.decode('utf-8').strip())
message = client_socket.recv(message_length).decode('utf-8')
print(f'{username} > {message}')
except:
continue
message = input(f'{username} > ')
if message:
message = bytes(message, 'utf-8')
message_header = f'{len(message):<10}'.encode('utf-8')
client_socket.send(message_header + message)
```
阅读全文