qt使用tcp互发信息
时间: 2024-10-22 16:27:45 浏览: 15
在Qt中,使用TCP进行双向通信需要两个部分:服务器和客户端。这里是一个简单的例子展示如何让它们互相发送信息。
**服务器(Server.cpp):**
```cpp
#include <QTcpServer>
#include <QDataStream>
#include <QObject>
class Server : public QObject {
Q_OBJECT
public slots:
void processClientMessage(const QByteArray &message) {
// 对接收到的消息进行处理
emit messageReceived(message);
}
signals:
void messageReceived(const QByteArray &message);
private:
QTcpServer *server;
QQueue<QByteArray> messages; // 存储来自客户端的消息队列
};
```
**服务器端主程序:**
```cpp
void Server::handleNewConnection() {
QTcpSocket *clientSocket = server->nextPendingConnection();
connect(clientSocket, &QTcpSocket::readyRead, this, [this](QTcpSocket *socket) {
QByteArray buffer = socket->readAll();
processClientMessage(buffer);
});
connect(clientSocket, &QTcpSocket::disconnected, this, &Server::closeConnection);
}
// 接收并广播接收到的消息
void Server::messageReceived(const QByteArray &message) {
emit broadcastMessage(message);
}
void Server::broadcastMessage(const QByteArray &message) {
for (auto client : clients) {
client->write(message);
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Server server;
return app.exec();
}
```
**客户端(Client.cpp):**
```cpp
#include <QTcpSocket>
#include <QDataStream>
#include <QObject>
class Client : public QObject {
Q_OBJECT
public slots:
void sendMessage(const QByteArray &message) {
connectedSocket.write(message);
}
private:
QTcpSocket *connectedSocket;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Client client;
client.connectedSocket = new QTcpSocket(&client);
connect(client.connectedSocket, &QTcpSocket::connected, &client, []{
client.sendMessage("Client is ready to send");
});
connect(client.connectedSocket, &QTcpSocket::disconnected, &app, &QApplication::quit);
// 连接到服务器
if (!client.connectedSocket->connectToHost("localhost", 12345)) {
qDebug() << "Failed to connect to the server.";
return -1;
}
return app.exec();
}
```
在这个例子中,服务器接收客户端发送的信息,将其存储然后通过`messageReceived`信号广播给其他已连接的客户端。客户端则在连接上建立后发送一条消息。
阅读全文