qt tcp客户端的例子
时间: 2023-08-28 07:07:58 浏览: 96
下面是一个简单的QT TCP客户端的例子,可以用来连接服务器并发送、接收数据。
```cpp
#include <QtNetwork>
#include <QTcpSocket>
class TcpClient : public QObject
{
Q_OBJECT
public:
TcpClient(QObject *parent = 0);
public slots:
void connectToServer();
void sendMessage(const QString &message);
private slots:
void readData();
void displayError(QAbstractSocket::SocketError socketError);
private:
QTcpSocket *tcpSocket;
};
TcpClient::TcpClient(QObject *parent)
: QObject(parent)
{
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
void TcpClient::connectToServer()
{
tcpSocket->connectToHost("localhost", 8000);
}
void TcpClient::sendMessage(const QString &message)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_9);
out << quint16(0) << message;
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
}
void TcpClient::readData()
{
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_5_9);
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
quint16 blockSize;
in >> blockSize;
if (tcpSocket->bytesAvailable() < blockSize)
return;
QString message;
in >> message;
qDebug() << "Received message: " << message;
}
void TcpClient::displayError(QAbstractSocket::SocketError socketError)
{
qDebug() << "Socket error: " << tcpSocket->errorString();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TcpClient client;
client.connectToServer();
client.sendMessage("Hello, server!");
return a.exec();
}
```
这个例子中,TcpClient 类继承自 QObject,包含了连接服务器、发送消息、读取数据和处理错误等功能。其中,connectToServer() 方法用于连接服务器,sendMessage() 方法用于发送消息,readData() 方法用于读取数据,displayError() 方法用于处理错误。
在 main() 函数中,首先创建了 TcpClient 的实例,然后调用 connectToServer() 方法连接服务器,并通过 sendMessage() 方法发送一条消息。最后调用 a.exec() 进入事件循环,等待数据的读取和错误的处理。
阅读全文