httpserver.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "httpserver.h"
  2. HttpServer &HttpServer::instance()
  3. {
  4. static HttpServer obj;
  5. return obj;
  6. }
  7. void HttpServer::run(const QHostAddress &address, const quint16 &port)
  8. {
  9. m_httpServer->listen(address,port);
  10. }
  11. void HttpServer::newConnection()
  12. {
  13. qDebug() << "newConnection";
  14. QTcpSocket *m_socket = m_httpServer->nextPendingConnection();
  15. QObject::connect(m_socket,&QTcpSocket::readyRead,this,&HttpServer::readyRead);
  16. }
  17. void HttpServer::readyRead()
  18. {
  19. static int index = 0;
  20. QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
  21. if(socket){
  22. QByteArray request = socket->readAll();
  23. if(index<10)
  24. qDebug() << "Request Data:" << request;
  25. index++;
  26. if(index>1)
  27. {
  28. mMutex.lock();
  29. mba.append(request);
  30. mMutex.unlock();
  31. }
  32. // qDebug("len: %d ",request.length());
  33. // static int count = 0;
  34. // count++;
  35. // QByteArray response = QString("<h1><center>Hello World %1</center></h1>\r\n").arg(count).toUtf8();
  36. // QString http = "HTTP/1.1 200 OK\r\n";
  37. // http += "Server: nginx\r\n";
  38. // http += "Content-Type: text/html;charset=utf-8\r\n";
  39. // http += "Connection: keep-alive\r\n";
  40. // http += QString("Content-Length: %1\r\n\r\n").arg(QString::number(response.size()));
  41. // socket->write(http.toUtf8());
  42. // socket->write(response);
  43. // socket->flush();
  44. // socket->waitForBytesWritten(http.size() + response.size());
  45. // socket->close();
  46. }
  47. }
  48. HttpServer::HttpServer(QObject *parent) : QObject(parent)
  49. {
  50. m_httpServer = new QTcpServer(this);
  51. m_httpServer->setMaxPendingConnections(1024);//设置最大允许连接数
  52. QObject::connect(m_httpServer,&QTcpServer::newConnection,this,&HttpServer::newConnection);
  53. }
  54. HttpServer::~HttpServer()
  55. {
  56. }
  57. QByteArray HttpServer::GetData()
  58. {
  59. QByteArray ba;
  60. ba.clear();
  61. mMutex.lock();
  62. ba = mba;
  63. mba.clear();
  64. mMutex.unlock();
  65. return ba;
  66. }