Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Tcp client is not able to recieve data from pthon server
Forum Updated to NodeBB v4.3 + New Features

Tcp client is not able to recieve data from pthon server

Scheduled Pinned Locked Moved Unsolved Qt for Python
6 Posts 3 Posters 742 Views 1 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.
  • D Offline
    D Offline
    daisyvish
    wrote on 16 Mar 2021, 08:43 last edited by daisyvish
    #1

    hello ,
    i m trying to communicate python server with Qt client .python Server is able to receive data but Qt client is not able to receive data from server .server program in python is as fallows:
    PythonServer program:

    import socket
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    print('socket created')
    s.bind(("150.0.28.147",8080))
    s.listen(3)
    print('waiting for connection')
    while True:
    c,addr=s.accept()
    print('connected with',addr)
    msg=("hello,welcome here")
    x=c.send(msg.encode())
    print(msg.encode())
    data=c.recv(1024)
    print('received:'+data.decode("utf8"))
    c.close()

    QTClient Program is as fallows:
    mainwindow.cpp :
    #include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(this, &MainWindow::newMessage, this, &MainWindow::displayMessage);
    connect(socket, &QTcpSocket::readyRead, this, &MainWindow::readSocket);
    connect(socket, &QTcpSocket::disconnected, this, &MainWindow::discardSocket);
    connect(socket, &QAbstractSocket::errorOccurred, this, &MainWindow::displayError);
    
    socket->connectToHost("150.0.28.147",8080);
    
    if(socket->waitForConnected())
        ui->statusBar->showMessage("Connected to Server");
    else{
        QMessageBox::critical(this,"QTCPClient", QString("The following error occurred: %1.").arg(socket->errorString()));
        exit(EXIT_FAILURE);
    }
    

    }

    MainWindow::~MainWindow()
    {
    if(socket->isOpen())
    socket->close();
    delete ui;
    }

    void MainWindow::readSocket()
    {
    QByteArray buffer;

    QDataStream socketStream(socket);
    socketStream.setVersion(QDataStream::Qt_5_15);
    
    socketStream.startTransaction();
    socketStream >> buffer;
    
    if(!socketStream.commitTransaction())
    {
        QString message = QString("%1 :: Waiting for more data to come..").arg(socket->socketDescriptor());
        emit newMessage(message);
        return;
    }
    
    QString header = buffer.mid(0,128);
    QString fileType = header.split(",")[0].split(":")[1];
    
    buffer = buffer.mid(128);
    
    if(fileType=="attachment"){
        QString fileName = header.split(",")[1].split(":")[1];
        QString ext = fileName.split(".")[1];
        QString size = header.split(",")[2].split(":")[1].split(";")[0];
    
        if (QMessageBox::Yes == QMessageBox::question(this, "QTCPServer", QString("You are receiving an attachment from sd:%1 of size: %2 bytes, called %3. Do you want to accept it?").arg(socket->socketDescriptor()).arg(size).arg(fileName)))
        {
            QString filePath = QFileDialog::getSaveFileName(this, tr("Save File"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/"+fileName, QString("File (*.%1)").arg(ext));
    
            QFile file(filePath);
            if(file.open(QIODevice::WriteOnly)){
                file.write(buffer);
                QString message = QString("INFO :: Attachment from sd:%1 successfully stored on disk under the path %2").arg(socket->socketDescriptor()).arg(QString(filePath));
                emit newMessage(message);
            }else
                QMessageBox::critical(this,"QTCPServer", "An error occurred while trying to write the attachment.");
        }else{
            QString message = QString("INFO :: Attachment from sd:%1 discarded").arg(socket->socketDescriptor());
            emit newMessage(message);
        }
    }else if(fileType=="message"){
        QString message = QString("%1 :: %2").arg(socket->socketDescriptor()).arg(QString::fromStdString(buffer.toStdString()));
        emit newMessage(message);
    }
    

    }

    void MainWindow::discardSocket()
    {
    socket->deleteLater();
    socket=nullptr;

    ui->statusBar->showMessage("Disconnected!");
    

    }

    void MainWindow::displayError(QAbstractSocket::SocketError socketError)
    {
    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
    break;
    case QAbstractSocket::HostNotFoundError:
    QMessageBox::information(this, "QTCPClient", "The host was not found. Please check the host name and port settings.");
    break;
    case QAbstractSocket::ConnectionRefusedError:
    QMessageBox::information(this, "QTCPClient", "The connection was refused by the peer. Make sure QTCPServer is running, and check that the host name and port settings are correct.");
    break;
    default:
    QMessageBox::information(this, "QTCPClient", QString("The following error occurred: %1.").arg(socket->errorString()));
    break;
    }
    }

    void MainWindow::on_pushButton_sendMessage_clicked()
    {
    if(socket)
    {
    if(socket->isOpen())
    {
    QString str = ui->lineEdit_message->text();

            QDataStream socketStream(socket);
            socketStream.setVersion(QDataStream::Qt_5_15);
    
            QByteArray header;
            header.prepend(QString("fileType:message,fileName:null,fileSize:%1;").arg(str.size()).toUtf8());
            header.resize(128);
    
            QByteArray byteArray = str.toUtf8();
            byteArray.prepend(header);
    
            socketStream << byteArray;
    
            ui->lineEdit_message->clear();
        }
        else
            QMessageBox::critical(this,"QTCPClient","Socket doesn't seem to be opened");
    }
    else
        QMessageBox::critical(this,"QTCPClient","Not connected");
    

    }

    void MainWindow::on_pushButton_sendAttachment_clicked()
    {
    if(socket)
    {
    if(socket->isOpen())
    {
    QString filePath = QFileDialog::getOpenFileName(this, ("Select an attachment"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), ("File (*.json *.txt *.png *.jpg *.jpeg)"));

            if(filePath.isEmpty()){
                QMessageBox::critical(this,"QTCPClient","You haven't selected any attachment!");
                return;
            }
    
            QFile m_file(filePath);
            if(m_file.open(QIODevice::ReadOnly)){
    
                QFileInfo fileInfo(m_file.fileName());
                QString fileName(fileInfo.fileName());
    
                QDataStream socketStream(socket);
                socketStream.setVersion(QDataStream::Qt_5_15);
    
                QByteArray header;
                header.prepend(QString("fileType:attachment,fileName:%1,fileSize:%2;").arg(fileName).arg(m_file.size()).toUtf8());
                header.resize(128);
    
                QByteArray byteArray = m_file.readAll();
                byteArray.prepend(header);
    
                socketStream.setVersion(QDataStream::Qt_5_15);
                socketStream << byteArray;
            }else
                QMessageBox::critical(this,"QTCPClient","Attachment is not readable!");
        }
        else
            QMessageBox::critical(this,"QTCPClient","Socket doesn't seem to be opened");
    }
    else
        QMessageBox::critical(this,"QTCPClient","Not connected");
    

    }

    void MainWindow::displayMessage(const QString& msg)
    {
    ui->textBrowser_receivedMessages->append(msg);
    }

    main.cpp :

    #include "mainwindow.h"
    #include <QApplication>

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
    }

    mainwindow.h :

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H

    #include <QMainWindow>
    #include <QAbstractSocket>
    #include <QDebug>
    #include <QFile>
    #include <QFileDialog>
    #include <QHostAddress>
    #include <QMessageBox>
    #include <QMetaType>
    #include <QString>
    #include <QStandardPaths>
    #include <QTcpSocket>

    namespace Ui {
    class MainWindow;
    }

    class MainWindow : public QMainWindow
    {
    Q_OBJECT

    public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    signals:
    void newMessage(QString);
    private slots:
    void readSocket();
    void discardSocket();
    void displayError(QAbstractSocket::SocketError socketError);

    void displayMessage(const QString& str);
    void on_pushButton_sendMessage_clicked();
    void on_pushButton_sendAttachment_clicked();
    

    private:
    Ui::MainWindow *ui;

    QTcpSocket* socket;
    

    };

    #endif // MAINWINDOW_H

    xml :

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
    <class>MainWindow</class>
    <widget class="QMainWindow" name="MainWindow">
    <property name="geometry">
    <rect>
    <x>0</x>
    <y>0</y>
    <width>369</width>
    <height>305</height>
    </rect>
    </property>
    <property name="windowTitle">
    <string>QTCPClient</string>
    </property>
    <property name="styleSheet">
    <string notr="true"/>
    </property>
    <widget class="QWidget" name="centralWidget">
    <layout class="QGridLayout" name="gridLayout_2">
    <item row="0" column="0">
    <widget class="QTextBrowser" name="textBrowser_receivedMessages">
    <property name="styleSheet">
    <string notr="true"/>
    </property>
    </widget>
    </item>
    <item row="1" column="0">
    <layout class="QGridLayout" name="gridLayout">
    <item row="1" column="0">
    <widget class="QPushButton" name="pushButton_sendMessage">
    <property name="styleSheet">
    <string notr="true"/>
    </property>
    <property name="text">
    <string>Send Message</string>
    </property>
    </widget>
    </item>
    <item row="1" column="1">
    <widget class="QPushButton" name="pushButton_sendAttachment">
    <property name="styleSheet">
    <string notr="true"/>
    </property>
    <property name="text">
    <string>Send Attachment</string>
    </property>
    </widget>
    </item>
    <item row="0" column="0" colspan="2">
    <widget class="QLineEdit" name="lineEdit_message">
    <property name="sizePolicy">
    <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
    <horstretch>0</horstretch>
    <verstretch>0</verstretch>
    </sizepolicy>
    </property>
    <property name="styleSheet">
    <string notr="true"/>
    </property>
    </widget>
    </item>
    </layout>
    </item>
    </layout>
    </widget>
    <widget class="QMenuBar" name="menuBar">
    <property name="geometry">
    <rect>
    <x>0</x>
    <y>0</y>
    <width>369</width>
    <height>21</height>
    </rect>
    </property>
    </widget>
    <widget class="QToolBar" name="mainToolBar">
    <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
    </attribute>
    <attribute name="toolBarBreak">
    <bool>false</bool>
    </attribute>
    </widget>
    <widget class="QStatusBar" name="statusBar"/>
    </widget>
    <layoutdefault spacing="6" margin="11"/>
    <resources/>
    <connections/>
    </ui>

    Please tell if any mistake has been done by me .....

    J P 2 Replies Last reply 16 Mar 2021, 08:56
    0
    • D daisyvish
      16 Mar 2021, 08:43

      hello ,
      i m trying to communicate python server with Qt client .python Server is able to receive data but Qt client is not able to receive data from server .server program in python is as fallows:
      PythonServer program:

      import socket
      s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
      print('socket created')
      s.bind(("150.0.28.147",8080))
      s.listen(3)
      print('waiting for connection')
      while True:
      c,addr=s.accept()
      print('connected with',addr)
      msg=("hello,welcome here")
      x=c.send(msg.encode())
      print(msg.encode())
      data=c.recv(1024)
      print('received:'+data.decode("utf8"))
      c.close()

      QTClient Program is as fallows:
      mainwindow.cpp :
      #include "mainwindow.h"
      #include "ui_mainwindow.h"

      MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MainWindow)
      {
      ui->setupUi(this);
      socket = new QTcpSocket(this);

      connect(this, &MainWindow::newMessage, this, &MainWindow::displayMessage);
      connect(socket, &QTcpSocket::readyRead, this, &MainWindow::readSocket);
      connect(socket, &QTcpSocket::disconnected, this, &MainWindow::discardSocket);
      connect(socket, &QAbstractSocket::errorOccurred, this, &MainWindow::displayError);
      
      socket->connectToHost("150.0.28.147",8080);
      
      if(socket->waitForConnected())
          ui->statusBar->showMessage("Connected to Server");
      else{
          QMessageBox::critical(this,"QTCPClient", QString("The following error occurred: %1.").arg(socket->errorString()));
          exit(EXIT_FAILURE);
      }
      

      }

      MainWindow::~MainWindow()
      {
      if(socket->isOpen())
      socket->close();
      delete ui;
      }

      void MainWindow::readSocket()
      {
      QByteArray buffer;

      QDataStream socketStream(socket);
      socketStream.setVersion(QDataStream::Qt_5_15);
      
      socketStream.startTransaction();
      socketStream >> buffer;
      
      if(!socketStream.commitTransaction())
      {
          QString message = QString("%1 :: Waiting for more data to come..").arg(socket->socketDescriptor());
          emit newMessage(message);
          return;
      }
      
      QString header = buffer.mid(0,128);
      QString fileType = header.split(",")[0].split(":")[1];
      
      buffer = buffer.mid(128);
      
      if(fileType=="attachment"){
          QString fileName = header.split(",")[1].split(":")[1];
          QString ext = fileName.split(".")[1];
          QString size = header.split(",")[2].split(":")[1].split(";")[0];
      
          if (QMessageBox::Yes == QMessageBox::question(this, "QTCPServer", QString("You are receiving an attachment from sd:%1 of size: %2 bytes, called %3. Do you want to accept it?").arg(socket->socketDescriptor()).arg(size).arg(fileName)))
          {
              QString filePath = QFileDialog::getSaveFileName(this, tr("Save File"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/"+fileName, QString("File (*.%1)").arg(ext));
      
              QFile file(filePath);
              if(file.open(QIODevice::WriteOnly)){
                  file.write(buffer);
                  QString message = QString("INFO :: Attachment from sd:%1 successfully stored on disk under the path %2").arg(socket->socketDescriptor()).arg(QString(filePath));
                  emit newMessage(message);
              }else
                  QMessageBox::critical(this,"QTCPServer", "An error occurred while trying to write the attachment.");
          }else{
              QString message = QString("INFO :: Attachment from sd:%1 discarded").arg(socket->socketDescriptor());
              emit newMessage(message);
          }
      }else if(fileType=="message"){
          QString message = QString("%1 :: %2").arg(socket->socketDescriptor()).arg(QString::fromStdString(buffer.toStdString()));
          emit newMessage(message);
      }
      

      }

      void MainWindow::discardSocket()
      {
      socket->deleteLater();
      socket=nullptr;

      ui->statusBar->showMessage("Disconnected!");
      

      }

      void MainWindow::displayError(QAbstractSocket::SocketError socketError)
      {
      switch (socketError) {
      case QAbstractSocket::RemoteHostClosedError:
      break;
      case QAbstractSocket::HostNotFoundError:
      QMessageBox::information(this, "QTCPClient", "The host was not found. Please check the host name and port settings.");
      break;
      case QAbstractSocket::ConnectionRefusedError:
      QMessageBox::information(this, "QTCPClient", "The connection was refused by the peer. Make sure QTCPServer is running, and check that the host name and port settings are correct.");
      break;
      default:
      QMessageBox::information(this, "QTCPClient", QString("The following error occurred: %1.").arg(socket->errorString()));
      break;
      }
      }

      void MainWindow::on_pushButton_sendMessage_clicked()
      {
      if(socket)
      {
      if(socket->isOpen())
      {
      QString str = ui->lineEdit_message->text();

              QDataStream socketStream(socket);
              socketStream.setVersion(QDataStream::Qt_5_15);
      
              QByteArray header;
              header.prepend(QString("fileType:message,fileName:null,fileSize:%1;").arg(str.size()).toUtf8());
              header.resize(128);
      
              QByteArray byteArray = str.toUtf8();
              byteArray.prepend(header);
      
              socketStream << byteArray;
      
              ui->lineEdit_message->clear();
          }
          else
              QMessageBox::critical(this,"QTCPClient","Socket doesn't seem to be opened");
      }
      else
          QMessageBox::critical(this,"QTCPClient","Not connected");
      

      }

      void MainWindow::on_pushButton_sendAttachment_clicked()
      {
      if(socket)
      {
      if(socket->isOpen())
      {
      QString filePath = QFileDialog::getOpenFileName(this, ("Select an attachment"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), ("File (*.json *.txt *.png *.jpg *.jpeg)"));

              if(filePath.isEmpty()){
                  QMessageBox::critical(this,"QTCPClient","You haven't selected any attachment!");
                  return;
              }
      
              QFile m_file(filePath);
              if(m_file.open(QIODevice::ReadOnly)){
      
                  QFileInfo fileInfo(m_file.fileName());
                  QString fileName(fileInfo.fileName());
      
                  QDataStream socketStream(socket);
                  socketStream.setVersion(QDataStream::Qt_5_15);
      
                  QByteArray header;
                  header.prepend(QString("fileType:attachment,fileName:%1,fileSize:%2;").arg(fileName).arg(m_file.size()).toUtf8());
                  header.resize(128);
      
                  QByteArray byteArray = m_file.readAll();
                  byteArray.prepend(header);
      
                  socketStream.setVersion(QDataStream::Qt_5_15);
                  socketStream << byteArray;
              }else
                  QMessageBox::critical(this,"QTCPClient","Attachment is not readable!");
          }
          else
              QMessageBox::critical(this,"QTCPClient","Socket doesn't seem to be opened");
      }
      else
          QMessageBox::critical(this,"QTCPClient","Not connected");
      

      }

      void MainWindow::displayMessage(const QString& msg)
      {
      ui->textBrowser_receivedMessages->append(msg);
      }

      main.cpp :

      #include "mainwindow.h"
      #include <QApplication>

      int main(int argc, char *argv[])
      {
      QApplication a(argc, argv);
      MainWindow w;
      w.show();
      return a.exec();
      }

      mainwindow.h :

      #ifndef MAINWINDOW_H
      #define MAINWINDOW_H

      #include <QMainWindow>
      #include <QAbstractSocket>
      #include <QDebug>
      #include <QFile>
      #include <QFileDialog>
      #include <QHostAddress>
      #include <QMessageBox>
      #include <QMetaType>
      #include <QString>
      #include <QStandardPaths>
      #include <QTcpSocket>

      namespace Ui {
      class MainWindow;
      }

      class MainWindow : public QMainWindow
      {
      Q_OBJECT

      public:
      explicit MainWindow(QWidget *parent = nullptr);
      ~MainWindow();
      signals:
      void newMessage(QString);
      private slots:
      void readSocket();
      void discardSocket();
      void displayError(QAbstractSocket::SocketError socketError);

      void displayMessage(const QString& str);
      void on_pushButton_sendMessage_clicked();
      void on_pushButton_sendAttachment_clicked();
      

      private:
      Ui::MainWindow *ui;

      QTcpSocket* socket;
      

      };

      #endif // MAINWINDOW_H

      xml :

      <?xml version="1.0" encoding="UTF-8"?>
      <ui version="4.0">
      <class>MainWindow</class>
      <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
      <rect>
      <x>0</x>
      <y>0</y>
      <width>369</width>
      <height>305</height>
      </rect>
      </property>
      <property name="windowTitle">
      <string>QTCPClient</string>
      </property>
      <property name="styleSheet">
      <string notr="true"/>
      </property>
      <widget class="QWidget" name="centralWidget">
      <layout class="QGridLayout" name="gridLayout_2">
      <item row="0" column="0">
      <widget class="QTextBrowser" name="textBrowser_receivedMessages">
      <property name="styleSheet">
      <string notr="true"/>
      </property>
      </widget>
      </item>
      <item row="1" column="0">
      <layout class="QGridLayout" name="gridLayout">
      <item row="1" column="0">
      <widget class="QPushButton" name="pushButton_sendMessage">
      <property name="styleSheet">
      <string notr="true"/>
      </property>
      <property name="text">
      <string>Send Message</string>
      </property>
      </widget>
      </item>
      <item row="1" column="1">
      <widget class="QPushButton" name="pushButton_sendAttachment">
      <property name="styleSheet">
      <string notr="true"/>
      </property>
      <property name="text">
      <string>Send Attachment</string>
      </property>
      </widget>
      </item>
      <item row="0" column="0" colspan="2">
      <widget class="QLineEdit" name="lineEdit_message">
      <property name="sizePolicy">
      <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
      <horstretch>0</horstretch>
      <verstretch>0</verstretch>
      </sizepolicy>
      </property>
      <property name="styleSheet">
      <string notr="true"/>
      </property>
      </widget>
      </item>
      </layout>
      </item>
      </layout>
      </widget>
      <widget class="QMenuBar" name="menuBar">
      <property name="geometry">
      <rect>
      <x>0</x>
      <y>0</y>
      <width>369</width>
      <height>21</height>
      </rect>
      </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
      <attribute name="toolBarArea">
      <enum>TopToolBarArea</enum>
      </attribute>
      <attribute name="toolBarBreak">
      <bool>false</bool>
      </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
      </widget>
      <layoutdefault spacing="6" margin="11"/>
      <resources/>
      <connections/>
      </ui>

      Please tell if any mistake has been done by me .....

      J Offline
      J Offline
      JonB
      wrote on 16 Mar 2021, 08:56 last edited by JonB
      #2

      @daisyvish
      This is an enormous piece of code for anyone to read through. What is the actual problem, what have you done in the way of debugging to locate whatever problem you have? Reduce it to a minimal example of whatever your issue is. You haven't even told us what output you get/do not get....

      D 1 Reply Last reply 17 Mar 2021, 08:31
      2
      • D daisyvish
        16 Mar 2021, 08:43

        hello ,
        i m trying to communicate python server with Qt client .python Server is able to receive data but Qt client is not able to receive data from server .server program in python is as fallows:
        PythonServer program:

        import socket
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        print('socket created')
        s.bind(("150.0.28.147",8080))
        s.listen(3)
        print('waiting for connection')
        while True:
        c,addr=s.accept()
        print('connected with',addr)
        msg=("hello,welcome here")
        x=c.send(msg.encode())
        print(msg.encode())
        data=c.recv(1024)
        print('received:'+data.decode("utf8"))
        c.close()

        QTClient Program is as fallows:
        mainwindow.cpp :
        #include "mainwindow.h"
        #include "ui_mainwindow.h"

        MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
        {
        ui->setupUi(this);
        socket = new QTcpSocket(this);

        connect(this, &MainWindow::newMessage, this, &MainWindow::displayMessage);
        connect(socket, &QTcpSocket::readyRead, this, &MainWindow::readSocket);
        connect(socket, &QTcpSocket::disconnected, this, &MainWindow::discardSocket);
        connect(socket, &QAbstractSocket::errorOccurred, this, &MainWindow::displayError);
        
        socket->connectToHost("150.0.28.147",8080);
        
        if(socket->waitForConnected())
            ui->statusBar->showMessage("Connected to Server");
        else{
            QMessageBox::critical(this,"QTCPClient", QString("The following error occurred: %1.").arg(socket->errorString()));
            exit(EXIT_FAILURE);
        }
        

        }

        MainWindow::~MainWindow()
        {
        if(socket->isOpen())
        socket->close();
        delete ui;
        }

        void MainWindow::readSocket()
        {
        QByteArray buffer;

        QDataStream socketStream(socket);
        socketStream.setVersion(QDataStream::Qt_5_15);
        
        socketStream.startTransaction();
        socketStream >> buffer;
        
        if(!socketStream.commitTransaction())
        {
            QString message = QString("%1 :: Waiting for more data to come..").arg(socket->socketDescriptor());
            emit newMessage(message);
            return;
        }
        
        QString header = buffer.mid(0,128);
        QString fileType = header.split(",")[0].split(":")[1];
        
        buffer = buffer.mid(128);
        
        if(fileType=="attachment"){
            QString fileName = header.split(",")[1].split(":")[1];
            QString ext = fileName.split(".")[1];
            QString size = header.split(",")[2].split(":")[1].split(";")[0];
        
            if (QMessageBox::Yes == QMessageBox::question(this, "QTCPServer", QString("You are receiving an attachment from sd:%1 of size: %2 bytes, called %3. Do you want to accept it?").arg(socket->socketDescriptor()).arg(size).arg(fileName)))
            {
                QString filePath = QFileDialog::getSaveFileName(this, tr("Save File"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)+"/"+fileName, QString("File (*.%1)").arg(ext));
        
                QFile file(filePath);
                if(file.open(QIODevice::WriteOnly)){
                    file.write(buffer);
                    QString message = QString("INFO :: Attachment from sd:%1 successfully stored on disk under the path %2").arg(socket->socketDescriptor()).arg(QString(filePath));
                    emit newMessage(message);
                }else
                    QMessageBox::critical(this,"QTCPServer", "An error occurred while trying to write the attachment.");
            }else{
                QString message = QString("INFO :: Attachment from sd:%1 discarded").arg(socket->socketDescriptor());
                emit newMessage(message);
            }
        }else if(fileType=="message"){
            QString message = QString("%1 :: %2").arg(socket->socketDescriptor()).arg(QString::fromStdString(buffer.toStdString()));
            emit newMessage(message);
        }
        

        }

        void MainWindow::discardSocket()
        {
        socket->deleteLater();
        socket=nullptr;

        ui->statusBar->showMessage("Disconnected!");
        

        }

        void MainWindow::displayError(QAbstractSocket::SocketError socketError)
        {
        switch (socketError) {
        case QAbstractSocket::RemoteHostClosedError:
        break;
        case QAbstractSocket::HostNotFoundError:
        QMessageBox::information(this, "QTCPClient", "The host was not found. Please check the host name and port settings.");
        break;
        case QAbstractSocket::ConnectionRefusedError:
        QMessageBox::information(this, "QTCPClient", "The connection was refused by the peer. Make sure QTCPServer is running, and check that the host name and port settings are correct.");
        break;
        default:
        QMessageBox::information(this, "QTCPClient", QString("The following error occurred: %1.").arg(socket->errorString()));
        break;
        }
        }

        void MainWindow::on_pushButton_sendMessage_clicked()
        {
        if(socket)
        {
        if(socket->isOpen())
        {
        QString str = ui->lineEdit_message->text();

                QDataStream socketStream(socket);
                socketStream.setVersion(QDataStream::Qt_5_15);
        
                QByteArray header;
                header.prepend(QString("fileType:message,fileName:null,fileSize:%1;").arg(str.size()).toUtf8());
                header.resize(128);
        
                QByteArray byteArray = str.toUtf8();
                byteArray.prepend(header);
        
                socketStream << byteArray;
        
                ui->lineEdit_message->clear();
            }
            else
                QMessageBox::critical(this,"QTCPClient","Socket doesn't seem to be opened");
        }
        else
            QMessageBox::critical(this,"QTCPClient","Not connected");
        

        }

        void MainWindow::on_pushButton_sendAttachment_clicked()
        {
        if(socket)
        {
        if(socket->isOpen())
        {
        QString filePath = QFileDialog::getOpenFileName(this, ("Select an attachment"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), ("File (*.json *.txt *.png *.jpg *.jpeg)"));

                if(filePath.isEmpty()){
                    QMessageBox::critical(this,"QTCPClient","You haven't selected any attachment!");
                    return;
                }
        
                QFile m_file(filePath);
                if(m_file.open(QIODevice::ReadOnly)){
        
                    QFileInfo fileInfo(m_file.fileName());
                    QString fileName(fileInfo.fileName());
        
                    QDataStream socketStream(socket);
                    socketStream.setVersion(QDataStream::Qt_5_15);
        
                    QByteArray header;
                    header.prepend(QString("fileType:attachment,fileName:%1,fileSize:%2;").arg(fileName).arg(m_file.size()).toUtf8());
                    header.resize(128);
        
                    QByteArray byteArray = m_file.readAll();
                    byteArray.prepend(header);
        
                    socketStream.setVersion(QDataStream::Qt_5_15);
                    socketStream << byteArray;
                }else
                    QMessageBox::critical(this,"QTCPClient","Attachment is not readable!");
            }
            else
                QMessageBox::critical(this,"QTCPClient","Socket doesn't seem to be opened");
        }
        else
            QMessageBox::critical(this,"QTCPClient","Not connected");
        

        }

        void MainWindow::displayMessage(const QString& msg)
        {
        ui->textBrowser_receivedMessages->append(msg);
        }

        main.cpp :

        #include "mainwindow.h"
        #include <QApplication>

        int main(int argc, char *argv[])
        {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
        return a.exec();
        }

        mainwindow.h :

        #ifndef MAINWINDOW_H
        #define MAINWINDOW_H

        #include <QMainWindow>
        #include <QAbstractSocket>
        #include <QDebug>
        #include <QFile>
        #include <QFileDialog>
        #include <QHostAddress>
        #include <QMessageBox>
        #include <QMetaType>
        #include <QString>
        #include <QStandardPaths>
        #include <QTcpSocket>

        namespace Ui {
        class MainWindow;
        }

        class MainWindow : public QMainWindow
        {
        Q_OBJECT

        public:
        explicit MainWindow(QWidget *parent = nullptr);
        ~MainWindow();
        signals:
        void newMessage(QString);
        private slots:
        void readSocket();
        void discardSocket();
        void displayError(QAbstractSocket::SocketError socketError);

        void displayMessage(const QString& str);
        void on_pushButton_sendMessage_clicked();
        void on_pushButton_sendAttachment_clicked();
        

        private:
        Ui::MainWindow *ui;

        QTcpSocket* socket;
        

        };

        #endif // MAINWINDOW_H

        xml :

        <?xml version="1.0" encoding="UTF-8"?>
        <ui version="4.0">
        <class>MainWindow</class>
        <widget class="QMainWindow" name="MainWindow">
        <property name="geometry">
        <rect>
        <x>0</x>
        <y>0</y>
        <width>369</width>
        <height>305</height>
        </rect>
        </property>
        <property name="windowTitle">
        <string>QTCPClient</string>
        </property>
        <property name="styleSheet">
        <string notr="true"/>
        </property>
        <widget class="QWidget" name="centralWidget">
        <layout class="QGridLayout" name="gridLayout_2">
        <item row="0" column="0">
        <widget class="QTextBrowser" name="textBrowser_receivedMessages">
        <property name="styleSheet">
        <string notr="true"/>
        </property>
        </widget>
        </item>
        <item row="1" column="0">
        <layout class="QGridLayout" name="gridLayout">
        <item row="1" column="0">
        <widget class="QPushButton" name="pushButton_sendMessage">
        <property name="styleSheet">
        <string notr="true"/>
        </property>
        <property name="text">
        <string>Send Message</string>
        </property>
        </widget>
        </item>
        <item row="1" column="1">
        <widget class="QPushButton" name="pushButton_sendAttachment">
        <property name="styleSheet">
        <string notr="true"/>
        </property>
        <property name="text">
        <string>Send Attachment</string>
        </property>
        </widget>
        </item>
        <item row="0" column="0" colspan="2">
        <widget class="QLineEdit" name="lineEdit_message">
        <property name="sizePolicy">
        <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
        <horstretch>0</horstretch>
        <verstretch>0</verstretch>
        </sizepolicy>
        </property>
        <property name="styleSheet">
        <string notr="true"/>
        </property>
        </widget>
        </item>
        </layout>
        </item>
        </layout>
        </widget>
        <widget class="QMenuBar" name="menuBar">
        <property name="geometry">
        <rect>
        <x>0</x>
        <y>0</y>
        <width>369</width>
        <height>21</height>
        </rect>
        </property>
        </widget>
        <widget class="QToolBar" name="mainToolBar">
        <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
        </attribute>
        <attribute name="toolBarBreak">
        <bool>false</bool>
        </attribute>
        </widget>
        <widget class="QStatusBar" name="statusBar"/>
        </widget>
        <layoutdefault spacing="6" margin="11"/>
        <resources/>
        <connections/>
        </ui>

        Please tell if any mistake has been done by me .....

        P Offline
        P Offline
        Pablo J. Rogina
        wrote on 16 Mar 2021, 11:32 last edited by
        #3

        @daisyvish said in Tcp client is not able to recieve data from pthon server:
        Could it be possible an IP address mismatch between server & client?

        server

        SERVER_HOST = "150.0.28.55"
        SERVER_PORT = 5634

        client

        socket->connectToHost("150.0.28.147",8080);

        Upvote the answer(s) that helped you solve the issue
        Use "Topic Tools" button to mark your post as Solved
        Add screenshots via postimage.org
        Don't ask support requests via chat/PM. Please use the forum so others can benefit from the solution in the future

        D 1 Reply Last reply 17 Mar 2021, 09:15
        1
        • J JonB
          16 Mar 2021, 08:56

          @daisyvish
          This is an enormous piece of code for anyone to read through. What is the actual problem, what have you done in the way of debugging to locate whatever problem you have? Reduce it to a minimal example of whatever your issue is. You haven't even told us what output you get/do not get....

          D Offline
          D Offline
          daisyvish
          wrote on 17 Mar 2021, 08:31 last edited by daisyvish
          #4

          @JonB
          problem is that i m not able to get data from server...In short Qt client is not able to display any data from server .

          J 1 Reply Last reply 17 Mar 2021, 09:23
          0
          • P Pablo J. Rogina
            16 Mar 2021, 11:32

            @daisyvish said in Tcp client is not able to recieve data from pthon server:
            Could it be possible an IP address mismatch between server & client?

            server

            SERVER_HOST = "150.0.28.55"
            SERVER_PORT = 5634

            client

            socket->connectToHost("150.0.28.147",8080);

            D Offline
            D Offline
            daisyvish
            wrote on 17 Mar 2021, 09:15 last edited by
            #5

            @Pablo-J-Rogina
            now i have changed the python program here ip and port is same

            1 Reply Last reply
            0
            • D daisyvish
              17 Mar 2021, 08:31

              @JonB
              problem is that i m not able to get data from server...In short Qt client is not able to display any data from server .

              J Offline
              J Offline
              JonB
              wrote on 17 Mar 2021, 09:23 last edited by
              #6

              @daisyvish said in Tcp client is not able to recieve data from pthon server:

              problem is that i m not able to get data from server...In short Qt client is not able to display any data from server .

              And I wrote earlier:

              what have you done in the way of debugging to locate whatever problem you have?

              Reduce it to a minimal example of whatever your issue is.

              You haven't even told us what output you get/do not get.... [You have print() statements, yet do not bother to tell us which you do/do not see output from.]

              1 Reply Last reply
              0

              2/6

              16 Mar 2021, 08:56

              4 unread
              • Login

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