在QT环境下,封装一个TCP服务端监听端口,收发消息的工具类
时间: 2024-05-14 08:12:35 浏览: 221
端口监听工具
5星 · 资源好评率100%
以下是一个基本的TCP服务端监听端口,收发消息的工具类的封装示例,使用QT的QTcpServer和QTcpSocket实现:
```
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
class TcpServer : public QObject
{
Q_OBJECT
public:
explicit TcpServer(QObject *parent = nullptr) : QObject(parent)
{
server = new QTcpServer(this);
connect(server, &QTcpServer::newConnection, this, &TcpServer::newConnection);
}
~TcpServer()
{
server->close();
delete server;
}
bool listen(int port)
{
return server->listen(QHostAddress::Any, port);
}
signals:
void clientConnected(QTcpSocket *socket);
void clientDisconnected(QTcpSocket *socket);
void messageReceived(QTcpSocket *socket, const QByteArray &message);
private slots:
void newConnection()
{
QTcpSocket *socket = server->nextPendingConnection();
connect(socket, &QTcpSocket::disconnected, this, &TcpServer::clientDisconnected);
connect(socket, &QTcpSocket::readyRead, this, &TcpServer::readyRead);
emit clientConnected(socket);
}
void readyRead()
{
QTcpSocket *socket = static_cast<QTcpSocket *>(sender());
while (socket->bytesAvailable() > 0)
{
QByteArray data = socket->readAll();
emit messageReceived(socket, data);
}
}
private:
QTcpServer *server;
};
```
使用示例:
```
TcpServer tcpServer;
connect(&tcpServer, &TcpServer::clientConnected, this, &MyClass::onClientConnected);
connect(&tcpServer, &TcpServer::clientDisconnected, this, &MyClass::onClientDisconnected);
connect(&tcpServer, &TcpServer::messageReceived, this, &MyClass::onMessageReceived);
if (!tcpServer.listen(1234))
{
qWarning() << "Failed to listen on port 1234";
}
void MyClass::onClientConnected(QTcpSocket *socket)
{
qDebug() << "Client connected:" << socket->peerAddress().toString() << ":" << socket->peerPort();
}
void MyClass::onClientDisconnected(QTcpSocket *socket)
{
qDebug() << "Client disconnected:" << socket->peerAddress().toString() << ":" << socket->peerPort();
}
void MyClass::onMessageReceived(QTcpSocket *socket, const QByteArray &message)
{
qDebug() << "Message received from" << socket->peerAddress().toString() << ":" << socket->peerPort() << ":" << message;
}
```
这个工具类会监听指定的端口,并在有新的客户端连接时发出信号,同时也会在客户端断开连接时发出信号。当收到客户端的消息时,会发出信号,同时将消息的内容和发送消息的客户端对应的QTcpSocket对象一起传递给槽函数。可以在槽函数中处理收到的消息,回复客户端,或者进行其他操作。
阅读全文