基于Socket的网络聊天系统的设计与实现代码
时间: 2023-08-07 17:03:05 浏览: 89
基于Socket网络聊天系统的设计与实现.docx
5星 · 资源好评率100%
以下是一个基于Socket的简单网络聊天系统的设计与实现代码示例:
```python
# 服务器端代码
import socket
import threading
def handle_client(client_socket, client_address):
print(f"New connection from {client_address}")
while True:
# 接收客户端消息
data = client_socket.recv(1024).decode()
if not data:
# 客户端断开连接
print(f"Connection closed by {client_address}")
break
# 打印接收到的消息
print(f"Received message from {client_address}: {data}")
# 发送消息给客户端
response = f"You said: {data}"
client_socket.send(response.encode())
# 关闭客户端连接
client_socket.close()
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8888)
server_socket.bind(server_address)
server_socket.listen(5)
print("Server started, listening on", server_address)
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
# 创建新线程处理客户端连接
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
# 启动服务器
start_server()
```
```python
# 客户端代码
import socket
def start_client():
server_address = ('localhost', 8888)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(server_address)
while True:
# 发送消息给服务器
message = input("Enter message: ")
client_socket.send(message.encode())
if message == "exit":
# 客户端退出
break
# 接收服务器消息
response = client_socket.recv(1024).decode()
print("Server response:", response)
# 关闭客户端连接
client_socket.close()
# 启动客户端
start_client()
```
这段代码实现了一个简单的基于Socket的网络聊天系统。服务器端使用多线程处理多个客户端连接,每个客户端连接都会创建一个新线程来处理。服务器接收来自客户端的消息,并将接收到的消息发送回客户端。客户端通过输入消息发送给服务器,并接收服务器的响应。当客户端输入"exit"时,程序结束。
请注意,此示例代码仅用于演示基本原理,可能需要进一步优化和完善以适应实际应用场景。
阅读全文