netdiskclient.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "netdiskclient.h"
  2. NetDiskClient::NetDiskClient(QObject *parent)
  3. : QObject(parent)
  4. {
  5. m_socket = new QTcpSocket(this);
  6. m_ip = "127.0.0.1";
  7. m_port = 9002;
  8. }
  9. QString NetDiskClient::ip() const
  10. {
  11. return m_ip;
  12. }
  13. void NetDiskClient::setIp(const QString &ip)
  14. {
  15. m_ip = ip;
  16. }
  17. int NetDiskClient::port() const
  18. {
  19. return m_port;
  20. }
  21. void NetDiskClient::setPort(int port)
  22. {
  23. m_port = port;
  24. }
  25. bool NetDiskClient::connectHost()
  26. {
  27. m_socket->connectToHost(m_ip, m_port);
  28. m_isConnected = m_socket->isOpen();
  29. return m_isConnected;
  30. }
  31. bool NetDiskClient::isConnected() const
  32. {
  33. return m_isConnected;
  34. }
  35. void NetDiskClient::setIsConnected(bool isConnected)
  36. {
  37. m_isConnected = isConnected;
  38. }
  39. void NetDiskClient::uploadFile(QString filename)
  40. {
  41. qDebug() << filename;
  42. QCryptographicHash md5(QCryptographicHash::Md5);
  43. QFile file(filename);
  44. file.open(QIODevice::ReadOnly);
  45. QByteArray data = file.readAll();
  46. md5.addData(data);
  47. QString md5str = md5.result().toHex().toLower();
  48. if (!m_socket->isOpen())
  49. {
  50. m_socket->connectToHost(m_ip, m_port);
  51. }
  52. QString cmd = "upload\n";
  53. QByteArray cmdData;
  54. cmdData.append(cmd);
  55. m_socket->write(cmdData);
  56. m_socket->write(data);
  57. }
  58. void NetDiskClient::downloadFileByMd5(QString md5, QString fileName)
  59. {
  60. if (!m_socket->isOpen())
  61. {
  62. m_socket->connectToHost(m_ip, m_port);
  63. }
  64. QString cmd = "download\n";
  65. QByteArray cmdData;
  66. cmdData.append(cmd);
  67. m_socket->write(cmdData);
  68. cmdData.clear();
  69. cmdData.append(md5 + "\n");
  70. m_socket->write(cmdData);
  71. QByteArray data;
  72. while (m_socket->waitForReadyRead(10))
  73. {
  74. data.append(m_socket->readAll());
  75. }
  76. QFile file(fileName);
  77. file.open(QIODevice::WriteOnly);
  78. file.write(data);
  79. file.flush();
  80. file.close();
  81. }