Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to Listen Any One Client At A Time Using QTcpServer And QTcpSocket
Forum Updated to NodeBB v4.3 + New Features

How to Listen Any One Client At A Time Using QTcpServer And QTcpSocket

Scheduled Pinned Locked Moved Unsolved General and Desktop
3 Posts 3 Posters 695 Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Ketan__Patel__0011K Offline
    Ketan__Patel__0011K Offline
    Ketan__Patel__0011
    wrote on last edited by
    #1

    Hello Friends.....

    I Want To Connect And Listen Any One Client At A Time And Get Data From The Client

    My Client Side Code Is Ready But At Server Side Am Not Able To Connect Any Particular Client

    My Server Side Code Is :

                   #include "mainwindow.h"                   
                   #include "ui_mainwindow.h"          
                                              
                   MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)                   
                   {                 
                       ui->setupUi(this);
                
                       m_server = new QTcpServer();                   
                   }
            
                   MainWindow::~MainWindow() 
                   {
                       foreach (QTcpSocket* socket, connection_list)
                       {
                           socket->close();
                           socket->deleteLater();
                       }
    
                       m_server->close();
                       m_server->deleteLater();
    
                       delete ui;
                   }
    
                   void MainWindow::newConnection()
                   {   
                       while (m_server->hasPendingConnections())
                           appendToSocketList(m_server->nextPendingConnection());
                   }  
    
                   void MainWindow::appendToSocketList(QTcpSocket* socket)
                   {
                       connection_list.append(socket);
                       connect(socket, SIGNAL(readyRead()), this , SLOT(readSocket()));
                       connect(socket, SIGNAL(disconnected()), this , SLOT(discardSocket()));
                       displayMessage(QString("INFO::Client with sockd:%1 has just entered the room").arg(socket->socketDescriptor()));
                   }
    
                   void MainWindow::readSocket()
                   {
                   
                       QTcpSocket* socket = reinterpret_cast<QTcpSocket*>(sender());
                       QByteArray Data = socket->readAll();
    
                       qDebug() << Data;
    
                       QFile target;
    
                       target.setFileName("D:/1.jpg");
    
                       qDebug() << target.readAll();
                   
                       if (!target.open(QIODevice::WriteOnly | QIODevice::Append))
                       {
                          qDebug() << "Can't open file for written";
                          return;
                       }
                       target.write(Data);
                       target.close();
                   }
    
                   void MainWindow::discardSocket()                   
                   {                   
                       QTcpSocket* socket = reinterpret_cast<QTcpSocket*>(sender());
                                                         
                       for (int i=0;i<connection_list.size();i++)                   
                       {                   
                           if (connection_list.at(i) == socket)                   
                           {                   
                               connection_list.removeAt(i);                   
                               break;                   
                           }                   
                       }
                                                       
                       socket->deleteLater();                  
                   }
    
                   void MainWindow::on_pushButton_sendMessage_clicked()                   
                   {                  
                       QString receiver = this->ui->comboBox_receiver->currentText();
    
                       if(receiver=="Broadcast")
                       {
                           foreach (QTcpSocket *socket,connection_list)
                           {
                               sendMessage(socket);
                           }
                       }
                       else             
                       {                   
                           foreach (QTcpSocket *socket,connection_list)                   
                           {                   
                               if(socket->socketDescriptor() == receiver.toLongLong())                   
                               {                   
                                   sendMessage(socket);                   
                                   break;                   
                               }                   
                           }                   
                       }                   
                       this->ui->lineEdit_message->clear();                   
                   }
    
                   void MainWindow::sendMessage(QTcpSocket* socket)                   
                   {                   
                       if(socket)                   
                       {                   
                           if(socket->isOpen())                   
                           {                   
                               QString str = this->ui->lineEdit_message->text();
    
                               QFile file("h:/Test_Image.jpg");
    
                               if(!file.open(QIODevice::ReadWrite))
                                   qDebug() << "Can't Send";
    
                               Data = file.readAll();
                   
                               socket->write(Data);
    
                               if(!socket->waitForBytesWritten(-1))
                               {
                                   qDebug() << "writen Bytes error " << socket->errorString();
                               }
                           }
                           else
                           {
                               QMessageBox::critical(this,"QTCPServer","Socket doesn't seem to be opened");
                           }
                       }
                       else
                       {                   
                           QMessageBox::critical(this,"QTCPServer","Not connected");                   
                       }                   
                   }
                                                         
                   void MainWindow::displayMessage(const QString& str)
                   {                   
                       this->ui->textBrowser_receivedMessages->append(str);                   
                   }
    
                   void MainWindow::on_pushButton_clicked()                   
                   {                   
                       if(m_server->listen(QHostAddress(ui->lineedit_Ip->text()) 17116))                   
                       {                                             connect(this,SIGNAL(newMessage(QString)),this,SLOT(displayMessage(QString)));                   
                          connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection()));
    
                          this->ui->statusBar->showMessage("Server is listening...");                   
                       }                   
                       else                   
                       {                   
                           QMessageBox::critical(this,"QTCPServer",QString("Unable to start the server: %1.").arg(m_server->errorString()));                   
                           exit(EXIT_FAILURE);                   
                       }                 
                   }
    

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    You Can See In PushButton Click Event

    When I Click On This Button

    It Give Me Error -> "Unable to start the server . This Address Is Not available

    I Want To Listen And Particular Client By Using It's Address And Get Data From It's

    I Am Not Getting Any Solution

    But

    When I Used This :

                   if(m_server->listen(QHostAddress::AnyIPv4 17116))
    

    That Time It Working

    But I Want to pass Any Particular IP Address in QHostAddress("IP_ADDRESS")

    Please Help Me To Solve My Problem

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      You can't pass any and all addresses you want to listen. It has to be one that is used by your machine if you have severals.

      On a side note, please turn off whatever plugin you are using that make all your words starting with a capital letter. It makes your post hard to read.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      3
      • Kent-DorfmanK Offline
        Kent-DorfmanK Offline
        Kent-Dorfman
        wrote on last edited by
        #3

        @Ketan__Patel__0011 said in How to Listen Any One Client At A Time Using QTcpServer And QTcpSocket:

        My Client Side Code Is Ready But At Server Side Am Not Able To Connect Any Particular Client

        Servers don't connect to clients. Clients connect to servers. The client initiates the session, and the server decided if it wants to accept the connection. It can selectively do so based on the IP of the incoming connection but it is the client that initiates.

        1 Reply Last reply
        4

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved