c++ qt 聊天系统
时间: 2023-12-01 10:04:51 浏览: 74
以下是一个使用C++和QT开发的简单聊天系统的示例:
```cpp
#include <QtWidgets/QApplication>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkInterface>
#include <QtCore/QList>
class ChatServer : public QTcpServer {
Q_OBJECT
public:
ChatServer(QObject *parent = 0) : QTcpServer(parent) {}
protected:
void incomingConnection(qintptr socketDescriptor) {
ChatSocket *socket = new ChatSocket(this);
socket->setSocketDescriptor(socketDescriptor);
emit newConnection(socket);
}
signals:
void newConnection(ChatSocket *socket);
};
class ChatSocket : public QTcpSocket {
Q_OBJECT
public:
ChatSocket(QObject *parent = 0) : QTcpSocket(parent) {
connect(this, SIGNAL(readyRead()), this, SLOT(readData()));
connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
}
public slots:
void readData() {
while (canReadLine()) {
QByteArray line = readLine();
emit messageReceived(line);
}
}
void sendMessage(const QString &message) {
write(message.toUtf8());
}
signals:
void messageReceived(const QString &message);
};
class ChatWindow : public QWidget {
Q_OBJECT
public:
ChatWindow(QWidget *parent = 0) : QWidget(parent) {
QVBoxLayout *layout = new QVBoxLayout(this);
messages = new QTextEdit(this); messages->setReadOnly(true);
layout->addWidget(messages);
QHBoxLayout *inputLayout = new QHBoxLayout();
input = new QLineEdit(this);
inputLayout->addWidget(input);
QPushButton *sendButton = new QPushButton(tr("Send"), this);
inputLayout->addWidget(sendButton);
layout->addLayout(inputLayout);
connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
}
void setSocket(ChatSocket *socket) {
connect(socket, SIGNAL(messageReceived(QString)), this, SLOT(receiveMessage(QString)));
connect(this, SIGNAL(sendMessage(QString)), socket, SLOT(sendMessage(QString)));
}
public slots:
void receiveMessage(const QString &message) {
messages->append(message);
}
void sendMessage() {
QString message = input->text();
emit sendMessage(message);
input->clear();
}
private:
QTextEdit *messages;
QLineEdit *input;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
ChatServer server;
QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
for (int i = 0; i < addresses.size(); i++) {
if (addresses[i].protocol() == QAbstractSocket::IPv4Protocol && !addresses[i].isLoopback()) {
server.listen(addresses[i], 1234);
break;
}
}
ChatWindow window;
QObject::connect(&server, SIGNAL(newConnection(ChatSocket*)), &window, SLOT(setSocket(ChatSocket*)));
window.show();
return app.exec();
}
```
这个聊天系统使用QTcpServer和QTcpSocket类来处理客户端连接和消息传递。服务器监听来自局域网下的客户端连接,并将消息转发给所有连接的客户端。客户端可以发送消息并接收其他客户端发送的消息。
阅读全文