用python写一个聊天室项目
时间: 2023-09-02 15:06:11 浏览: 159
基于Python + MQTT实现的的聊天室项目源码+数据库,实现登录、注册、多个聊天室切换,保存以往聊天记录
5星 · 资源好评率100%
好的,我可以给你提供一个简单的聊天室项目的Python代码,使用Socket编程实现。以下是服务器端和客户端代码。
服务器端代码:
```python
import socket
import threading
# 服务器的IP地址和端口号
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8000
# 创建一个socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind((SERVER_HOST, SERVER_PORT))
# 开始监听客户端的连接请求
server_socket.listen()
# 存储所有客户端socket的列表
client_sockets = []
# 存储所有客户端的昵称
nicknames = []
# 处理客户端的连接请求
def handle_client_connection(client_socket):
while True:
try:
# 接收来自客户端的消息
message = client_socket.recv(1024).decode('utf-8')
# 如果客户端断开连接,则移除客户端socket和昵称
if message == 'QUIT':
index = client_sockets.index(client_socket)
client_sockets.remove(client_socket)
client_socket.close()
nickname = nicknames[index]
nicknames.remove(nickname)
print(f'{nickname} has left the chat room!')
break
# 将消息发送给所有客户端
else:
print(f'{nicknames[client_sockets.index(client_socket)]}: {message}')
for socket in client_sockets:
socket.send(f'{nicknames[client_sockets.index(client_socket)]}: {message}'.encode('utf-8'))
except:
# 如果客户端断开连接,则移除客户端socket和昵称
index = client_sockets.index(client_socket)
client_sockets.remove(client_socket)
client_socket.close()
nickname = nicknames[index]
nicknames.remove(nickname)
print(f'{nickname} has left the chat room!')
break
# 接受客户端的连接请求并创建一个新的线程处理连接
def accept_client_connections():
while True:
# 接受客户端的连接请求
client_socket, client_address = server_socket.accept()
print(f'New client connected: {client_address}')
# 获取客户端的昵称
client_socket.send('Enter your nickname: '.encode('utf-8'))
nickname = client_socket.recv(1024).decode('utf-8')
nicknames.append(nickname)
client_sockets.append(client_socket)
print(f'Nickname of the client is {nickname}')
# 发送欢迎消息给客户端
client_socket.send('Welcome to the chat room!'.encode('utf-8'))
# 创建一个新的线程处理客户端的连接
thread = threading.Thread(target=handle_client_connection, args=(client_socket,))
thread.start()
if __name__ == '__main__':
print(f'Server is running on {SERVER_HOST}:{SERVER_PORT}')
# 启动一个线程接受客户端的连接请求
accept_thread = threading.Thread(target=accept_client_connections)
accept_thread.start()
```
客户端代码:
```python
import socket
import threading
# 服务器的IP地址和端口号
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 8000
# 创建一个socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect((SERVER_HOST, SERVER_PORT))
# 获取客户端的昵称
nickname = input('Enter your nickname: ')
# 发送昵称给服务器
client_socket.send(nickname.encode('utf-8'))
# 接收来自服务器的消息
def receive():
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
print(message)
except:
# 如果服务器断开连接,则退出程序
client_socket.close()
break
# 发送消息给服务器
def send():
while True:
message = input('')
client_socket.send(message.encode('utf-8'))
if message == 'QUIT':
client_socket.close()
break
if __name__ == '__main__':
# 创建两个线程分别处理接收和发送消息
receive_thread = threading.Thread(target=receive)
receive_thread.start()
send_thread = threading.Thread(target=send)
send_thread.start()
```
在运行聊天室之前,请确保您已经安装了Python和Socket模块。如果您想在本地运行此聊天室,请在服务器和客户端代码中使用相同的IP地址和端口号。
阅读全文