写一个Qt的Tcp的类的代码
时间: 2024-11-12 17:35:47 浏览: 11
在Qt中,你可以创建一个简单的TCP客户端或服务器类来处理网络通信。这里是一个基本的TCP服务器示例,它使用了`QTcpServer`和`QTcpSocket`。注意,实际应用中可能需要添加错误处理和信号槽连接等更复杂的功能。
```cpp
#include <QObject>
#include <QTcpServer>
class TcpServer : public QObject
{
Q_OBJECT
public:
explicit TcpServer(QObject *parent = nullptr)
: QObject(parent), server(new QTcpServer(this))
{
if (!server->listen(QHostAddress::Any, 12345)) // 设置监听地址和端口
{
qCritical() << "Failed to start TCP server: " << server->errorString();
return;
}
connect(server, &QTcpServer::newConnection, this, &TcpServer::acceptNewConnection);
}
private slots:
void acceptNewConnection()
{
QTcpSocket* socket = server->nextPendingConnection(); // 接受新连接
if (socket) {
connect(socket, &QTcpSocket::disconnected, this, &TcpServer::handleClientDisconnect);
qDebug() << "Accepted new client connection from" << socket->peerAddress().toString();
emit newClientConnected(socket); // 发布信号通知处理新连接
} else {
qWarning() << "Failed to accept connection";
}
}
void handleClientDisconnect()
{
qDebug() << "Client disconnected at " << QDateTime::currentDateTime().toString();
}
signals:
void newClientConnected(QTcpSocket *clientSocket);
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
TcpServer server;
return app.exec();
}
```
在这个例子中,`TcpServer`继承自`QObject`,并在构造函数中启动TCP服务器。当有新的客户端连接时,会触发`acceptNewConnection`槽函数,然后处理新连接并发出`newClientConnected`信号。`handleClientDisconnect`槽函数用于处理客户端断开连接的情况。
阅读全文