Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Tcp client is not able to recieve data from pthon server



  • 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 .....



  • @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....



  • @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);



  • @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 .



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



  • @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.]


Log in to reply