qt tcp socket 通信实例
时间: 2024-09-13 14:16:24 浏览: 44
Qt TCP套接字通信实例通常用于客户端和服务器之间的双向数据传输,例如聊天应用、游戏服务器等。以下是使用Qt C++的一个简单示例:
首先,你需要包含必要的头文件并设置基本的TCP服务器:
```cpp
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
class Server : public QObject
{
Q_OBJECT
public slots:
void startServer() {
QTcpServer *server = new QTcpServer(this);
if (server->listen(QHostAddress::Any, 8080)) { // 监听所有地址的8080端口
while (!server->isListening()) { // 当服务器开始监听时
qApp->processEvents(); // 保持应用程序活跃
}
connect(server, &QTcpServer::newConnection, this, &Server::handleNewConnection); // 连接到新连接事件
qDebug() << "Server is listening on port 8080";
} else {
qDebug() << "Failed to listen on port 8080";
}
}
private slots:
void handleNewConnection() {
QTcpSocket *socket = server->nextPendingConnection();
connect(socket, &QTcpSocket::readyRead, this, &Server::handleDataReceived);
connect(socket, &QObject::destroyed, this, &Server::removeSocket);
}
void handleDataReceived() {
QByteArray data = socket->readAll();
emit sendDataToClient(data); // 发送给处理数据的部分
}
void removeSocket(QObject *sender) {
delete sender; // 删除已断开的连接
}
};
```
然后,你可以创建一个`Client`类,进行相应的TCP连接请求:
```cpp
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject *parent = nullptr) : QObject(parent), socket(new QTcpSocket(this)) {}
public slots:
void connectToServer(const QString &host, quint16 port) {
socket->connectToHost(host, port);
connect(socket, &QTcpSocket::connected, this, &Client::sendHelloMessage);
connect(socket, &QTcpSocket::error, this, &Client::connectionError);
}
private slots:
void sendHelloMessage() {
socket->write("Hello from client!"); // 发送一条消息到服务器
}
void connectionError() {
qDebug() << "Connection error";
}
signals:
void receiveDataFromServer(const QByteArray &data); // 信号发射接收的数据
protected:
QTcpSocket *socket;
};
```
要在客户端和服务器之间传递数据,需要在`Server`类中添加信号处理器,并在`Client`类中对接收的信号作出响应:
```cpp
void Server::sendDataToClient(const QByteArray &data) {
emit sendDataToClient(data); // 发送给客户端的信号
}
void Client::receiveDataFromServer(const QByteArray &data) {
qDebug() << "Received message: " << data.toUtf8().constData();
}
```
最后,在主程序中初始化服务器和客户端:
```cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Server server;
connect(&app, &QApplication::aboutToQuit, &server, &Server::quit); // 关闭服务器时关闭应用
server.startServer();
Client client;
client.connectToServer("localhost", 8080); // 如果是本地测试,主机名通常为"localhost"
return app.exec();
}
```
阅读全文