qt tcp客户端接收
时间: 2023-08-28 20:04:44 浏览: 158
以下是使用Qt编写的TCP客户端代码,可以接收从服务器发送的消息:
```cpp
#include <QtNetwork>
#include <QtWidgets>
class TcpClient : public QWidget
{
Q_OBJECT
public:
TcpClient(QWidget *parent = nullptr);
private slots:
void requestNewConnection();
void readData();
void displayError(QAbstractSocket::SocketError socketError);
private:
QLabel *statusLabel;
QTcpSocket *tcpSocket;
QDataStream in;
};
TcpClient::TcpClient(QWidget *parent)
: QWidget(parent)
{
statusLabel = new QLabel(tr("Not connected to server."));
QPushButton *connectButton = new QPushButton(tr("Connect"));
connect(connectButton, &QPushButton::clicked, this, &TcpClient::requestNewConnection);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(statusLabel);
layout->addWidget(connectButton);
setLayout(layout);
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::readData);
connect(tcpSocket, &QTcpSocket::disconnected, tcpSocket, &QTcpSocket::deleteLater);
connect(tcpSocket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &TcpClient::displayError);
}
void TcpClient::requestNewConnection()
{
QString hostName = QInputDialog::getText(this, tr("Connect to Server"), tr("Host name:"));
if (hostName.isEmpty()) {
return;
}
int port = QInputDialog::getInt(this, tr("Connect to Server"), tr("Port number:"), 1234, 1, 65535);
if (port <= 0) {
return;
}
tcpSocket->connectToHost(hostName, port);
if (!tcpSocket->waitForConnected(3000)) {
statusLabel->setText(tr("Failed to connect to server."));
return;
}
statusLabel->setText(tr("Connected to server."));
in.setDevice(tcpSocket);
in.setVersion(QDataStream::Qt_5_15);
}
void TcpClient::readData()
{
QString message;
in.startTransaction();
in >> message;
if (!in.commitTransaction()) {
return;
}
statusLabel->setText(tr("Received message: %1").arg(message));
}
void TcpClient::displayError(QAbstractSocket::SocketError socketError)
{
QString errorMessage;
switch (socketError) {
case QAbstractSocket::HostNotFoundError:
errorMessage = tr("The host was not found.");
break;
case QAbstractSocket::RemoteHostClosedError:
errorMessage = tr("The remote host is closed.");
break;
case QAbstractSocket::ConnectionRefusedError:
errorMessage = tr("The connection was refused.");
break;
default:
errorMessage = tcpSocket->errorString();
}
statusLabel->setText(tr("Error: %1").arg(errorMessage));
}
```
在这个例子中,我们使用了`QTcpSocket`类来与服务器建立连接,并且使用`QDataStream`类来读取从服务器发送过来的数据。`QTcpSocket`类提供了`readyRead()`信号,该信号在有新的数据可用时会被触发,我们在`readData()`函数中处理这些数据。如果接收到的数据无法被成功读取,则会回滚事务并等待下一次读取。`QAbstractSocket::error()`信号在连接发生错误时会被触发,我们在`displayError()`函数中处理这些错误。
阅读全文