以下是一个使用Qt编写的TCP客户端,可以接收来自服务器的消息:
#include <QtNetwork>
#include <QtWidgets>
class TcpClient : public QWidget
{
Q_OBJECT
public:
TcpClient(QWidget *parent = nullptr);
private slots:
void connectToServer();
void readData();
void displayError(QAbstractSocket::SocketError socketError);
private:
QLineEdit *hostLineEdit;
QLineEdit *portLineEdit;
QTextEdit *messageTextEdit;
QPushButton *connectButton;
QTcpSocket *tcpSocket;
};
TcpClient::TcpClient(QWidget *parent)
: QWidget(parent)
{
QLabel *hostLabel = new QLabel(tr("Host name:"));
hostLineEdit = new QLineEdit("localhost");
QLabel *portLabel = new QLabel(tr("Port number:"));
portLineEdit = new QLineEdit("1234");
connectButton = new QPushButton(tr("Connect"));
connectButton->setDefault(true);
QHBoxLayout *topLayout = new QHBoxLayout;
topLayout->addWidget(hostLabel);
topLayout->addWidget(hostLineEdit);
topLayout->addWidget(portLabel);
topLayout->addWidget(portLineEdit);
topLayout->addWidget(connectButton);
messageTextEdit = new QTextEdit;
messageTextEdit->setReadOnly(true);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(topLayout);
mainLayout->addWidget(messageTextEdit);
setLayout(mainLayout);
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::readData);
connect(tcpSocket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
this, &TcpClient::displayError);
connect(connectButton, &QPushButton::clicked, this, &TcpClient::connectToServer);
}
void TcpClient::connectToServer()
{
QString hostName = hostLineEdit->text();
quint16 port = portLineEdit->text().toUShort();
tcpSocket->connectToHost(hostName, port);
}
void TcpClient::readData()
{
QByteArray data = tcpSocket->readAll();
messageTextEdit->append(data);
}
void TcpClient::displayError(QAbstractSocket::SocketError socketError)
{
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
QMessageBox::information(this, tr("TCP Client"),
tr("The host was not found. Please check the "
"host name and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
QMessageBox::information(this, tr("TCP Client"),
tr("The connection was refused by the peer. "
"Make sure the server is running, "
"and check that the host name and port "
"settings are correct."));
break;
default:
QMessageBox::information(this, tr("TCP Client"),
tr("The following error occurred: %1.")
.arg(tcpSocket->errorString()));
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TcpClient client;
client.show();
return app.exec();
}
#include "main.moc"
该客户端使用Qt的QTcpSocket类来与服务器建立TCP连接,并在接收到数据时将其显示在QTextEdit小部件中。在connectToServer()函数中,我们使用hostLineEdit和portLineEdit小部件中的值来连接到服务器。在readData()函数中,我们使用tcpSocket->readAll()读取来自服务器的所有数据。在displayError()函数中,我们处理与连接错误相关的各种情况。