123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- #include "mainwindow.h"
- #include "ui_mainwindow.h"
- #include "QTcpSocket"
- #include "QTcpServer"
- #include "myserver.h"
- #include "QNetworkInterface"
- #include "QHostInfo"
- MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
- {
- ui->setupUi(this);
- setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);
- setFixedSize(214,155);
- ui->label->setText("<font color='red'>Assistant is closed</font>");
- udpSocket=new QUdpSocket(this);
- connect(udpSocket, SIGNAL(readyRead()),this,SLOT(on_upd_received()));
- udpSocket->bind(5678);
- }
- MainWindow::~MainWindow()
- {
- server.close();
- udpSocket->close();
- delete ui;
- }
- void MainWindow::on_pushButton_clicked()
- {
- if(started==0){
- server.StartServer();
- started=1;
- ui->pushButton->setText("CLOSE");
- ui->label->setText("<font color='green'>Assistant is running</font>");
- }else{
- server.close();
- started=0;
- ui->pushButton->setText("OPEN");
- ui->label->setText("<font color='red'>Assistant is closed</font>");
- }
- }
- void MainWindow::on_upd_received()
- {
- while(udpSocket->hasPendingDatagrams())
- {
- QByteArray datagram;
- datagram.resize(udpSocket->pendingDatagramSize());
- udpSocket->readDatagram(datagram.data(),datagram.size());
- QString msg=datagram.data();
- qDebug()<<msg;
- QStringList request=msg.split(" ");
- if(request.size()>1){
- if(!(request.at(0).compare("requestip"))&&started==1){
- QString requstIp=request.at(1);
- qDebug()<<"ip: "<<requstIp;
- QString myIp=getHostIp();
- QString myName=getHostName();
- qDebug()<<myIp;
- QTcpSocket* answerSocket=new QTcpSocket();
- answerSocket->connectToHost(requstIp,1234);
- answerSocket->write(myName.append(",").append(myIp).toUtf8());
- answerSocket->close();
- }
- }
- }
- }
- QString MainWindow::getHostIp(){
- QString str="";
- QList<QHostAddress> netList = QNetworkInterface::allAddresses();
- for(int i=0;i<netList.count();i++){
- QHostAddress ip=netList.at(i);
- if(ip.protocol()==QAbstractSocket::IPv4Protocol){
- str.append("|").append(netList.at(i).toString());
- }
- }
- return str;
- }
- QString MainWindow::getHostName(){
- QString name= QHostInfo::localHostName();
- return name;
- }
|