例1 客户端
#include <QTcpSocket>
#include <QHostAddress>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, 1234);
if (socket.waitForConnected()) {
socket.write("Hello, server!");
if (socket.waitForBytesWritten()) {
if (socket.waitForReadyRead()) {
qDebug() << "Received data:" << socket.readAll();
}
}
}
return app.exec();
}
例2 服务端
#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>
class MyTcpServer : public QTcpServer
{
Q_OBJECT
public:
explicit MyTcpServer(QObject *parent = 0) : QTcpServer(parent)
{
if (!this->listen(QHostAddress::Any, 1234)) {
QMessageBox::critical(0, "Server Error", "Unable to start the server:" + this->errorString());
exit(EXIT_FAILURE);
}
}
protected:
void incomingConnection(qintptr socketDescriptor) override
{
QTcpSocket* socket = new QTcpSocket(this);
socket->setSocketDescriptor(socketDescriptor);
connect(socket, &QTcpSocket::readyRead, this, [socket]() {
QByteArray data = socket->readAll();
qDebug() << "Received data:" << data;
socket->write("Hello, client!");
});
connect(socket, &QTcpSocket::disconnected, this, [socket]() {
qDebug() << "Client disconnected:" << socket->peerAddress().toString();
socket->deleteLater();
});
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyTcpServer server;
return app.exec();
}
Qt 的 TCP 类(QTcpSocket 和 QTcpServer)创建简单的 TCP 客户端和服务器。在示例 1 中,我们创建了一个 TCP 客户端,连接到本地主机上的端口 1234,并发送一条消息给服务器。在示例 2 中,我们创建了一个 TCP 服务器,监听本地主机上的端口 1234,并在接收到客户端连接时发送一条消息给客户端。这些示例可以作为你开始使用 Qt TCP 通信的基础。