mainwindow.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. #include "QTcpSocket"
  4. #include "QTcpServer"
  5. #include "myserver.h"
  6. #include "QNetworkInterface"
  7. #include "QHostInfo"
  8. MainWindow::MainWindow(QWidget *parent) :
  9. QMainWindow(parent),
  10. ui(new Ui::MainWindow)
  11. {
  12. ui->setupUi(this);
  13. setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);
  14. setFixedSize(214,155);
  15. ui->label->setText("<font color='red'>Assistant is closed</font>");
  16. udpSocket=new QUdpSocket(this);
  17. connect(udpSocket, SIGNAL(readyRead()),this,SLOT(on_upd_received()));
  18. udpSocket->bind(5678);
  19. }
  20. MainWindow::~MainWindow()
  21. {
  22. server.close();
  23. udpSocket->close();
  24. delete ui;
  25. }
  26. void MainWindow::on_pushButton_clicked()
  27. {
  28. if(started==0){
  29. server.StartServer();
  30. started=1;
  31. ui->pushButton->setText("CLOSE");
  32. ui->label->setText("<font color='green'>Assistant is running</font>");
  33. }else{
  34. server.close();
  35. started=0;
  36. ui->pushButton->setText("OPEN");
  37. ui->label->setText("<font color='red'>Assistant is closed</font>");
  38. }
  39. }
  40. void MainWindow::on_upd_received()
  41. {
  42. while(udpSocket->hasPendingDatagrams())
  43. {
  44. QByteArray datagram;
  45. datagram.resize(udpSocket->pendingDatagramSize());
  46. udpSocket->readDatagram(datagram.data(),datagram.size());
  47. QString msg=datagram.data();
  48. qDebug()<<msg;
  49. QStringList request=msg.split(" ");
  50. if(request.size()>1){
  51. if(!(request.at(0).compare("requestip"))&&started==1){
  52. QString requstIp=request.at(1);
  53. qDebug()<<"ip: "<<requstIp;
  54. QString myIp=getHostIp();
  55. QString myName=getHostName();
  56. qDebug()<<myIp;
  57. QTcpSocket* answerSocket=new QTcpSocket();
  58. answerSocket->connectToHost(requstIp,1234);
  59. answerSocket->write(myName.append(",").append(myIp).toUtf8());
  60. answerSocket->close();
  61. }
  62. }
  63. }
  64. }
  65. QString MainWindow::getHostIp(){
  66. QString str="";
  67. QList<QHostAddress> netList = QNetworkInterface::allAddresses();
  68. for(int i=0;i<netList.count();i++){
  69. QHostAddress ip=netList.at(i);
  70. if(ip.protocol()==QAbstractSocket::IPv4Protocol){
  71. str.append("|").append(netList.at(i).toString());
  72. }
  73. }
  74. return str;
  75. }
  76. QString MainWindow::getHostName(){
  77. QString name= QHostInfo::localHostName();
  78. return name;
  79. }