qt TCP Socket 客户端
时间: 2023-06-26 12:03:47 浏览: 127
下面是一个简单的 Qt TCP Socket 客户端示例代码:
```cpp
#include <QTcpSocket>
#include <QHostAddress>
void MyClient::connectToHost(const QString& ip, int port)
{
m_socket = new QTcpSocket(this);
connect(m_socket, &QTcpSocket::connected, this, &MyClient::onConnected);
connect(m_socket, &QTcpSocket::disconnected, this, &MyClient::onDisconnected);
connect(m_socket, &QTcpSocket::readyRead, this, &MyClient::onReadyRead);
m_socket->connectToHost(QHostAddress(ip), port);
}
void MyClient::sendData(const QByteArray& data)
{
m_socket->write(data);
}
void MyClient::onConnected()
{
qDebug() << "Connected to server";
}
void MyClient::onDisconnected()
{
qDebug() << "Disconnected from server";
}
void MyClient::onReadyRead()
{
QByteArray data = m_socket->readAll();
qDebug() << "Received data: " << data;
}
```
在上面的代码中,我们首先创建了一个 QTcpSocket 对象,并连接了它的一些信号和槽。然后,我们通过调用 `connectToHost` 函数连接到服务器。一旦连接建立,`onConnected` 槽将被调用。然后,我们可以通过调用 `sendData` 函数向服务器发送数据。当服务器发送数据时,`onReadyRead` 槽将被调用,我们可以在其中读取数据。最后,当连接断开时,`onDisconnected` 槽将被调用。
阅读全文
相关推荐
















