帮我写一个有服务端和客户端的python socket 网络聊天室
时间: 2023-11-03 07:04:11 浏览: 82
好的,以下是一个简单的Python socket网络聊天室的代码示例。其中包括了服务端和客户端的实现。
服务端代码:
```python
import socket
import threading
HOST = 'localhost'
PORT = 8888
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址
server_socket.bind((HOST, PORT))
# 最大连接数
server_socket.listen(10)
# 存储连接的客户端
clients = []
def broadcast(message):
"""
广播消息给所有连接的客户端
"""
for client in clients:
client.send(message)
def handle_client(client_socket, client_address):
"""
处理客户端连接
"""
print(f'New client {client_address} has joined')
clients.append(client_socket)
while True:
try:
# 接收客户端消息
message = client_socket.recv(1024)
if message:
print(f'Received message from {client_address}: {message.decode()}')
# 广播消息给所有连接的客户端
broadcast(message)
else:
# 客户端断开连接
print(f'Client {client_address} has disconnected')
clients.remove(client_socket)
client_socket.close()
break
except:
# 客户端出现异常
print(f'Client {client_address} has encountered an error')
clients.remove(client_socket)
client_socket.close()
break
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
# 创建新线程处理客户端连接
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
```
客户端代码:
```python
import socket
import threading
HOST = 'localhost'
PORT = 8888
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect((HOST, PORT))
def receive():
"""
接收服务器消息
"""
while True:
try:
message = client_socket.recv(1024)
print(message.decode())
except:
# 出现异常
client_socket.close()
break
def send():
"""
发送消息给服务器
"""
while True:
message = input('')
client_socket.send(message.encode())
# 创建两个线程,分别处理接收和发送消息
receive_thread = threading.Thread(target=receive)
send_thread = threading.Thread(target=send)
receive_thread.start()
send_thread.start()
```
注意:此代码示例仅供参考,并不具备完整的错误处理和安全性控制。在实际应用中,需要根据具体情况进行修改和优化。
阅读全文