用qt写一段封装socket功能的代码
时间: 2023-06-05 17:04:27 浏览: 132
好的,以下是我为您编写的一段封装socket功能的代码:
```
#include <QTcpSocket>
class SocketClient : public QObject
{
Q_OBJECT
public:
SocketClient(QObject *parent = nullptr) : QObject(parent), socket(new QTcpSocket(this)) {}
void connectToHost(const QString &hostname, quint16 port)
{
socket->connectToHost(hostname, port);
}
void disconnectFromHost()
{
socket->disconnectFromHost();
}
bool isConnected() const
{
return socket->state() == QTcpSocket::ConnectedState;
}
signals:
void connected();
void disconnected();
void error(const QString &message);
void messageReceived(const QString &message);
public slots:
void send(const QString &message)
{
if (isConnected()) {
socket->write(message.toUtf8());
socket->flush();
} else {
emit error("Not connected to a host.");
}
}
private slots:
void onConnected()
{
emit connected();
connect(socket, &QTcpSocket::readyRead, this, &SocketClient::readSocket);
}
void onDisconnected()
{
disconnect(socket, &QTcpSocket::readyRead, this, &SocketClient::readSocket);
emit disconnected();
}
void onError(QAbstractSocket::SocketError error)
{
QString errorMessage = QString("Socket error: %1").arg(socket->errorString());
emit error(errorMessage);
}
void readSocket()
{
QByteArray data = socket->readAll();
QString message(data);
emit messageReceived(message);
}
private:
QTcpSocket *socket;
};
```
这段代码实现了一个 SocketClient 类,可以通过 connectToHost() 方法连接到指定的主机和端口,并通过 isConnected() 方法判断是否连接成功。使用 send() 方法可以向主机发送文本消息。该类提供了 connected()、disconnected()、error() 和 messageReceived() 四个信号,用于通知连接、断开连接、出错和接收到消息的事件。socket 对象的各种事件在 onConnected()、onDisconnected()、onError() 和 readSocket() 四个槽函数中进行处理。
阅读全文