python实现群聊功能: 客户端能发送文本和文件消息(暂时支持文本和文件) 客户端每隔一秒向服务器请求最新的群消息(也就是服务器收到的所有客户端的消息),如果有新消息,就显示出新消息 要求: 客户端采用QT5实现 客户端与服务端的通讯要求使用thrift
时间: 2024-02-20 10:01:55 浏览: 153
好的,以下是一个简单的Python实现群聊功能的示例:
客户端代码:
```python
import sys
import time
import os
import thriftpy2
from thriftpy2.rpc import make_client
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
chat_thrift = thriftpy2.load("chat.thrift", module_name="chat_thrift")
class ChatClient(QWidget):
def __init__(self):
super().__init__()
self.username = ""
self.setup_ui()
self.connect_server()
def setup_ui(self):
self.chat_record = QTextEdit()
self.chat_record.setReadOnly(True)
self.chat_input = QTextEdit()
self.send_button = QPushButton("发送")
self.file_button = QPushButton("发送文件")
self.file_button.setEnabled(False)
self.check_timer = QTimer(self)
self.check_timer.timeout.connect(self.check_new_message)
self.check_timer.start(1000)
layout = QVBoxLayout()
layout.addWidget(self.chat_record)
layout.addWidget(self.chat_input)
button_layout = QHBoxLayout()
button_layout.addWidget(self.send_button)
button_layout.addWidget(self.file_button)
layout.addLayout(button_layout)
self.setLayout(layout)
self.setWindowTitle("群聊")
self.resize(600, 400)
self.send_button.clicked.connect(self.send_message)
self.file_button.clicked.connect(self.send_file)
def connect_server(self):
self.client = make_client(chat_thrift.ChatService, "localhost", 9090)
self.username, success = QInputDialog.getText(self, "登录", "请输入您的用户名:")
if success:
self.file_button.setEnabled(True)
def send_message(self):
message = self.chat_input.toPlainText()
if message:
self.client.send_message(self.username, message)
self.chat_input.clear()
def send_file(self):
file_path, _ = QFileDialog.getOpenFileName(self, "选择文件", ".", "All files(*.*)")
if file_path:
with open(file_path, "rb") as f:
file_data = f.read()
file_name = os.path.basename(file_path)
self.client.send_file(self.username, file_name, file_data)
def check_new_message(self):
new_messages = self.client.get_messages()
if new_messages:
for message in new_messages:
sender, content = message.sender, message.content
self.chat_record.append(f"{sender}: {content}")
if __name__ == '__main__':
app = QApplication(sys.argv)
client = ChatClient()
client.show()
sys.exit(app.exec_())
```
服务端代码:
```python
import thriftpy2
from thriftpy2.rpc import make_server
chat_thrift = thriftpy2.load("chat.thrift", module_name="chat_thrift")
class ChatServiceHandler:
def __init__(self):
self.messages = []
def send_message(self, sender, content):
self.messages.append(chat_thrift.Message(sender=sender, content=content))
print(f"{sender}: {content}")
def send_file(self, sender, file_name, file_data):
self.messages.append(chat_thrift.Message(sender=sender, content=f"发送了文件 {file_name}"))
print(f"{sender} 发送了文件 {file_name}")
def get_messages(self):
messages = self.messages
self.messages = []
return messages
if __name__ == '__main__':
handler = ChatServiceHandler()
server = make_server(chat_thrift.ChatService, handler, "localhost", 9090)
print("Starting the chat server...")
server.serve()
```
其中,`chat.thrift`文件的内容如下:
```thrift
namespace py chat_thrift
struct Message {
1: string sender,
2: string content,
}
service ChatService {
void send_message(1: string sender, 2: string content),
void send_file(1: string sender, 2: string file_name, 3: binary file_data),
list<Message> get_messages(),
}
```
在启动服务端后,运行客户端即可进行群聊,每隔一秒钟会自动请求最新的群消息并显示出来。客户端可以发送文本消息和文件消息。
阅读全文