帮我写一个在qt上运行的能够实现文件传输的TCP服务端
时间: 2024-02-19 07:58:05 浏览: 79
Qt实现TCP文件传输例子
4星 · 用户满意度95%
好的,以下是一个在Qt上运行的能够实现文件传输的TCP服务端的基本代码:
```
#include <QtNetwork>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
class Server : public QObject
{
Q_OBJECT
public:
explicit Server(QObject *parent = nullptr);
void start();
private slots:
void onNewConnection();
void onReadyRead();
void onDisconnected();
private:
QTcpServer *m_tcpServer;
QTcpSocket *m_tcpSocket;
};
Server::Server(QObject *parent) : QObject(parent)
{
m_tcpServer = new QTcpServer(this);
connect(m_tcpServer, &QTcpServer::newConnection, this, &Server::onNewConnection);
}
void Server::start()
{
if (!m_tcpServer->listen(QHostAddress::Any, 5555)) {
qDebug() << "Error: Could not start server.";
return;
}
qDebug() << "Server started.";
}
void Server::onNewConnection()
{
m_tcpSocket = m_tcpServer->nextPendingConnection();
connect(m_tcpSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead);
connect(m_tcpSocket, &QTcpSocket::disconnected, this, &Server::onDisconnected);
qDebug() << "New client connected.";
}
void Server::onReadyRead()
{
QByteArray data = m_tcpSocket->readAll();
qDebug() << "Received: " << data;
// Write file to disk
QFile file("received_file.txt");
if (file.open(QIODevice::WriteOnly)) {
file.write(data);
file.close();
qDebug() << "File saved to disk.";
}
// Send response
m_tcpSocket->write("File received.");
}
void Server::onDisconnected()
{
qDebug() << "Client disconnected.";
m_tcpSocket->deleteLater();
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Server server;
server.start();
return app.exec();
}
#include "main.moc"
```
这个服务端程序监听5555端口,当有客户端连接进来时,会读取客户端发送来的文件并将其保存到磁盘上,然后向客户端发送一个简单的回复。你可以根据实际需求修改代码来实现更复杂的功能。
阅读全文