网络编程实操题
时间: 2023-07-05 19:06:54 浏览: 59
以下是一个基于Socket的简单的聊天室实操题。
要求:
1. 实现一个多人在线聊天室,可以支持多个客户端连接到服务器并进行聊天。
2. 客户端可以输入用户名,服务器会记录下来并将其显示在聊天室中。
3. 客户端可以输入消息并发送给其他客户端,服务器会将其转发给所有连接到服务器的客户端。
4. 实现基本的异常处理,例如客户端异常断开连接、服务器异常关闭等情况。
提示:
1. 可以使用Python的socket模块来实现网络通信。
2. 服务器可以使用单线程或多线程的方式实现,可以考虑使用select模块来实现多路复用。
3. 客户端可以使用命令行或简单的图形界面来实现。
代码示例:
服务器端代码:
```python
import socket
HOST = '127.0.0.1' # Server IP address
PORT = 8888 # Server port
BUFSIZ = 1024 # Buffer size
ADDR = (HOST, PORT)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(ADDR)
server_socket.listen(5)
print('Server started at {}:{}'.format(HOST, PORT))
# List of client sockets
client_sockets = []
while True:
# Wait for a new client connection
client_socket, client_addr = server_socket.accept()
print('Client {}:{} connected'.format(client_addr[0], client_addr[1]))
# Add the new client socket to the list
client_sockets.append(client_socket)
# Send a welcome message to the new client
client_socket.send('Welcome to the chat room! Please enter your username:'.encode('utf-8'))
# Receive the username of the new client
username = client_socket.recv(BUFSIZ).decode('utf-8')
print('Client {}:{} username is {}'.format(client_addr[0], client_addr[1], username))
# Send a welcome message to all clients
for sock in client_sockets:
if sock != client_socket:
sock.send('{} joined the chat room!'.format(username).encode('utf-8'))
# Start a new thread to handle the client connection
# You can also use select() to handle multiple connections in the same thread
while True:
try:
data = client_socket.recv(BUFSIZ)
if not data:
break
# Broadcast the message to all clients
for sock in client_sockets:
if sock != client_socket:
sock.send('[{}] {}: {}'.format(username, client_addr[0], data.decode('utf-8')).encode('utf-8'))
except Exception as e:
print('Client {}:{} error: {}'.format(client_addr[0], client_addr[1], e))
break
# Remove the client socket from the list
client_sockets.remove(client_socket)
# Send a leave message to all clients
for sock in client_sockets:
sock.send('{} left the chat room!'.format(username).encode('utf-8'))
# Close the client socket
client_socket.close()
# Close the server socket
server_socket.close()
```
客户端代码:
```python
import socket
import threading
HOST = '127.0.0.1' # Server IP address
PORT = 8888 # Server port
BUFSIZ = 1024 # Buffer size
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
# Receive messages from the server
def receive():
while True:
try:
data = client_socket.recv(BUFSIZ)
print(data.decode('utf-8'))
except Exception as e:
print('Error: {}'.format(e))
break
# Start a new thread to receive messages from the server
receive_thread = threading.Thread(target=receive)
receive_thread.start()
# Send messages to the server
username = input('Please enter your username:')
client_socket.send(username.encode('utf-8'))
while True:
try:
message = input('')
if message == 'quit':
break
client_socket.send(message.encode('utf-8'))
except Exception as e:
print('Error: {}'.format(e))
break
# Close the client socket
client_socket.close()
```
运行方式:
1. 在终端中运行服务器端代码:`python server.py`
2. 在多个终端中分别运行客户端代码:`python client.py`
3. 在客户端中输入用户名并发送消息即可在聊天室中进行聊天,输入`quit`退出程序。