Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Mobile and Embedded
  4. I can't receive QTcpServer Socket message on Android
Forum Updated to NodeBB v4.3 + New Features

I can't receive QTcpServer Socket message on Android

Scheduled Pinned Locked Moved Unsolved Mobile and Embedded
3 Posts 2 Posters 299 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.
  • DewyD Offline
    DewyD Offline
    Dewy
    wrote on last edited by
    #1

    Hello all,

    NetworkManager.h

    // networkmanager.h
    #ifndef NETWORKMANAGER_H
    #define NETWORKMANAGER_H
    
    #include <QObject>
    #include <QString>
    #include <QNetworkInterface>
    #include <QTcpServer>
    #include <QTcpSocket>
    
    #include "hdr/constants.h"
    
    class NetworkManager : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(ConnectionStatus connectionStatus READ connectionStatus WRITE setConnectionStatus NOTIFY connectionStatusChanged)
    
    public:
        explicit NetworkManager(QObject *parent = nullptr);
    
        QString getMacAddress();
        QTcpSocket* clientSocket;
    
        ConnectionStatus connectionStatus();
    
    public slots:
        void setConnectionStatus(ConnectionStatus status);
    
    private:
        QNetworkInterface findActiveNetworkInterface();
        QHostAddress m_address;
        int m_port;
    
        ConnectionStatus m_connectionStatus;
    
    signals:
        void connectionStatusChanged();
    };
    
    #endif // NETWORKMANAGER_H
    
    

    NetworkManager.cpp

    #include "hdr/managers/networkmanager.h"
    
    NetworkManager::NetworkManager(QObject *parent)
        : QObject(parent),
          m_address("192.168.1.153"),
          m_port(1453),
          m_connectionStatus(ConnectionStatus::Disconnected)
    {
        clientSocket = new QTcpSocket(this);
        clientSocket->connectToHost(m_address,m_port);
    }
    
    QString NetworkManager::getMacAddress()
    {
        QNetworkInterface activeInterface = findActiveNetworkInterface();
        if (!activeInterface.isValid()) {
            return QString();
        }
    
        QByteArray macBytes = activeInterface.hardwareAddress().toUtf8();
        QString macAddress = QString(macBytes.toHex(':')).toUpper(); // Convert QByteArray to formatted QString
        return macAddress;
    }
    
    ConnectionStatus NetworkManager::connectionStatus()
    {
        return m_connectionStatus;
    }
    
    void NetworkManager::setConnectionStatus(ConnectionStatus status)
    {
        if(m_connectionStatus == status)
            return;
    
        m_connectionStatus = status;
    
        emit connectionStatusChanged();
    }
    
    QNetworkInterface NetworkManager::findActiveNetworkInterface()
    {
        QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
        foreach (QNetworkInterface interface, interfaces) {
            if (!(interface.flags() & QNetworkInterface::IsLoopBack) &&
                (interface.flags() & QNetworkInterface::IsUp) &&
                (interface.flags() & QNetworkInterface::IsRunning)) {
                return interface;
            }
        }
        return QNetworkInterface(); // Invalid interface
    }
    

    ApplicationManager.cpp

    
    void ApplicationManager::initObjects()
    {
        nManager = new NetworkManager();
        if (nManager->clientSocket->waitForConnected()) {
            nManager->setConnectionStatus(ConnectionStatus::Connected);
    
            qDebug() << "Connection Successful.";
    
            QByteArray veri = "Hello Server!";
            nManager->clientSocket->write(veri);
            nManager->clientSocket->flush();
            nManager->clientSocket->waitForBytesWritten();
    
            connect(nManager->clientSocket, &QTcpSocket::readyRead, this, [=](){
                qDebug() <<"Data came!";
            });
    
    //        connect(nManager->clientSocket, &QTcpSocket::readyRead, this, &ApplicationManager::readData);
    //        connect(nManager->clientSocket, SIGNAL(readyRead()), this, SLOT(readData()));
        }
    }
    

    myserver.h

    #ifndef MYSERVER_H
    #define MYSERVER_H
    
    #include <QObject>
    #include <QTcpServer>
    #include <QTcpSocket>
    #include <QAbstractSocket>
    
    #include "myclient.h"
    
    class MyServer : public QTcpServer
    {
        Q_OBJECT
    public:
        explicit MyServer(QObject *parent = nullptr);
        void startServer();
    
    public slots:
        void newCon();
        void readyRead();
        void sockDisc();
    
    protected:
        QTcpSocket *socket;
    //    void incomingConnection(int handle);
    };
    
    #endif // MYSERVER_H
    

    myserver.cpp

    #include "myserver.h"
    
    MyServer::MyServer(QObject *parent) :
        QTcpServer(parent)
    {
    }
    
    void MyServer::startServer()
    {
        if (listen(QHostAddress::Any, 1453))
        {
            connect(this, &QTcpServer::newConnection, this, &MyServer::newCon);
            qDebug() << "started";
        }
        else
        {
            qDebug() << "not started";
        }
    }
    
    void MyServer::newCon()
    {
        socket = nextPendingConnection();
    
        if(socket == nullptr)
        {
            qDebug() << "No new socket...";
            return;
        }
        connect(socket,&QTcpSocket::readyRead,this,&MyServer::readyRead);
        connect(socket,&QTcpSocket::disconnected, this,&MyServer::sockDisc);
    
        socket->write("You are connect");
        socket->flush();
        socket->waitForBytesWritten();
        qDebug()<<"Send client connect status - YES";
    }
    
    void MyServer::readyRead()
    {
        qDebug() << socket->readAll();
    }
    
    void MyServer::sockDisc()
    {
        qDebug()<<"Disconnect";
        socket->deleteLater();
    }
    

    Hello All,
    I created an android application using Qt 5.15.2. The app connect to backend and the app can send message to server, but the application can't receive message correctly. I tested server application using nc and it works. also I tested the app on x86_64 and it worked too. But when I want to run it on Android, it doesn't work.

    Anybody can help me please?

    The main problem is that, android application cannot receive QTcpSocket message.

    Thanks!

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

      Hi,

      First thing: you should do all your connections prior to starting to use your objects.

      There's also nothing related to error management. You should add that as well.

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

      DewyD 1 Reply Last reply
      0
      • SGaistS SGaist

        Hi,

        First thing: you should do all your connections prior to starting to use your objects.

        There's also nothing related to error management. You should add that as well.

        DewyD Offline
        DewyD Offline
        Dewy
        wrote on last edited by Dewy
        #3

        @SGaist Hello,
        But main thing is that the project works on x86_64. But it doesn't work on Android. I added these permissions to AndroidManifest.xml file;

        <uses-permission android:name="android.permission.READ_CONTACTS"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        

        I updated my classes and i moved all things to NetworkManager class like that;

        Android NetworkManager.h

        // networkmanager.h
        #ifndef NETWORKMANAGER_H
        #define NETWORKMANAGER_H
        
        #include <QObject>
        #include <QString>
        #include <QNetworkInterface>
        #include <QTcpServer>
        #include <QTcpSocket>
        
        #include "hdr/constants.h"
        
        class NetworkManager : public QObject
        {
            Q_OBJECT
            Q_PROPERTY(ConnectionStatus connectionStatus READ connectionStatus WRITE setConnectionStatus NOTIFY connectionStatusChanged)
        
        public:
            explicit NetworkManager(QObject *parent = nullptr);
        
            QString getMacAddress();
            QTcpSocket* clientSocket;
        
            ConnectionStatus connectionStatus();
        
            QHostAddress address();
            int port();
        
        public slots:
            void setConnectionStatus(ConnectionStatus status);
        
            void readyRead();
        
        
        private:
            QNetworkInterface findActiveNetworkInterface();
            QHostAddress m_address;
            int m_port;
        
            ConnectionStatus m_connectionStatus;
        
        signals:
            void connectionStatusChanged();
        };
        
        #endif // NETWORKMANAGER_H
        

        Android NetworkManager.cpp

        #include "hdr/managers/networkmanager.h"
        
        NetworkManager::NetworkManager(QObject *parent)
            : QObject(parent),
              m_address("192.168.1.107"),
              m_port(1453),
              m_connectionStatus(ConnectionStatus::Disconnected)
        {
            clientSocket = new QTcpSocket(this);
        
        
        
            clientSocket->connectToHost(address(),port());
        
        
            if (clientSocket->waitForConnected()) {
        
                connect(clientSocket, &QTcpSocket::connected, this, [=](){
                    qDebug() << "[.] connected";
                });
                connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
                    qDebug() << "[.] disconnected";
                });
                connect(clientSocket, &QTcpSocket::readyRead,this, &NetworkManager::readyRead);
                connect(clientSocket, &QTcpSocket::errorOccurred, this, [=](QAbstractSocket::SocketError socketError) {
                    if (socketError == QAbstractSocket::RemoteHostClosedError) {
                        qDebug() << "Sunucu bağlantısı kapattı.";
                    } else if (socketError == QAbstractSocket::HostNotFoundError) {
                        qDebug() << "Sunucu bulunamadı.";
                    } else if (socketError == QAbstractSocket::ConnectionRefusedError) {
                        qDebug() << "Bağlantı reddedildi.";
                    } else {
                        qDebug() << "Bilinmeyen bir hata oluştu: " << clientSocket->errorString();
                    }
                });
        
                connect(clientSocket, &QTcpSocket::stateChanged, this, [=](QAbstractSocket::SocketState socketState) {
                    if (socketState == QAbstractSocket::ConnectedState) {
                        qDebug() << "Bağlantı başarılı.";
                    } else if (socketState == QAbstractSocket::UnconnectedState) {
                        qDebug() << "Bağlantı kesildi.";
                    }
                });
        
                setConnectionStatus(ConnectionStatus::Connected);
        
                qDebug() << "Connection Successful.";
        
                QByteArray veri = "Hello Server!";
                clientSocket->write(veri);
                clientSocket->flush();
                clientSocket->waitForBytesWritten();
            }
        }
        
        QString NetworkManager::getMacAddress()
        {
            QNetworkInterface activeInterface = findActiveNetworkInterface();
            if (!activeInterface.isValid()) {
                return QString();
            }
        
            QByteArray macBytes = activeInterface.hardwareAddress().toUtf8();
            QString macAddress = QString(macBytes.toHex(':')).toUpper(); // Convert QByteArray to formatted QString
            return macAddress;
        }
        
        ConnectionStatus NetworkManager::connectionStatus()
        {
            return m_connectionStatus;
        }
        
        QHostAddress NetworkManager::address()
        {
            return m_address;
        }
        
        int NetworkManager::port()
        {
            return m_port;
        }
        
        void NetworkManager::readyRead()
        {
            qDebug()<<"data received!";
        //    while (clientSocket->bytesAvailable() > 0) {
        //        QByteArray data = clientSocket->readAll();
        //        qDebug() << "Received data:" << data;
        //    }
        }
        
        void NetworkManager::setConnectionStatus(ConnectionStatus status)
        {
            if(m_connectionStatus == status)
                return;
        
            m_connectionStatus = status;
        
            emit connectionStatusChanged();
        }
        
        QNetworkInterface NetworkManager::findActiveNetworkInterface()
        {
            QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
            foreach (QNetworkInterface interface, interfaces) {
                if (!(interface.flags() & QNetworkInterface::IsLoopBack) &&
                    (interface.flags() & QNetworkInterface::IsUp) &&
                    (interface.flags() & QNetworkInterface::IsRunning)) {
                    return interface;
                }
            }
            return QNetworkInterface(); // Invalid interface
        }
        

        x86_64 NetworkManager.h

        // networkmanager.h
        #ifndef NETWORKMANAGER_H
        #define NETWORKMANAGER_H
        
        #include <QObject>
        #include <QString>
        #include <QNetworkInterface>
        #include <QTcpServer>
        #include <QTcpSocket>
        
        class NetworkManager : public QObject
        {
            Q_OBJECT
        
        public:
            explicit NetworkManager(QObject *parent = nullptr);
        
            QString getMacAddress();
            QTcpSocket* clientSocket;
        
            QHostAddress address();
            int port();
        
        
        public slots:
            void readyRead();
        
        private:
            QNetworkInterface findActiveNetworkInterface();
            QHostAddress m_address;
            int m_port;
        
        signals:
            void connectionStatusChanged();
        };
        
        #endif // NETWORKMANAGER_H
        

        x86_64 NetworkManager.cpp

        #include "networkmanager.h"
        
        NetworkManager::NetworkManager(QObject *parent)
            : QObject(parent),
              m_address("192.168.1.107"),
              m_port(1453)
        {
            clientSocket = new QTcpSocket(this);
            clientSocket->connectToHost(address(),port());
        
        
            if (clientSocket->waitForConnected()) {
        
                connect(clientSocket, &QTcpSocket::connected, this, [=](){
                    qDebug() << "[.] connected";
                });
                connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
                    qDebug() << "[.] disconnected";
                });
                connect(clientSocket, &QTcpSocket::readyRead,this, &NetworkManager::readyRead);
                connect(clientSocket, &QTcpSocket::errorOccurred, this, [=](QAbstractSocket::SocketError socketError) {
                    if (socketError == QAbstractSocket::RemoteHostClosedError) {
                        qDebug() << "Sunucu bağlantısı kapattı.";
                    } else if (socketError == QAbstractSocket::HostNotFoundError) {
                        qDebug() << "Sunucu bulunamadı.";
                    } else if (socketError == QAbstractSocket::ConnectionRefusedError) {
                        qDebug() << "Bağlantı reddedildi.";
                    } else {
                        qDebug() << "Bilinmeyen bir hata oluştu: " << clientSocket->errorString();
                    }
                });
        
                connect(clientSocket, &QTcpSocket::stateChanged, this, [=](QAbstractSocket::SocketState socketState) {
                    if (socketState == QAbstractSocket::ConnectedState) {
                        qDebug() << "Bağlantı başarılı.";
                    } else if (socketState == QAbstractSocket::UnconnectedState) {
                        qDebug() << "Bağlantı kesildi.";
                    }
                });
        
        
                qDebug() << "Connection Successful.";
        
                QByteArray veri = "Hello Server!";
                clientSocket->write(veri);
                clientSocket->flush();
                clientSocket->waitForBytesWritten();
            }
        }
        
        QString NetworkManager::getMacAddress()
        {
            QNetworkInterface activeInterface = findActiveNetworkInterface();
            if (!activeInterface.isValid()) {
                return QString();
            }
        
            QByteArray macBytes = activeInterface.hardwareAddress().toUtf8();
            QString macAddress = QString(macBytes.toHex(':')).toUpper(); // Convert QByteArray to formatted QString
            return macAddress;
        }
        
        QHostAddress NetworkManager::address()
        {
            return m_address;
        }
        
        int NetworkManager::port()
        {
            return m_port;
        }
        
        void NetworkManager::readyRead()
        {
            qDebug()<<"data received!";
        //    while (clientSocket->bytesAvailable() > 0) {
        //        QByteArray data = clientSocket->readAll();
        //        qDebug() << "Received data:" << data;
        //    }
        }
        
        QNetworkInterface NetworkManager::findActiveNetworkInterface()
        {
            QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
            foreach (QNetworkInterface interface, interfaces) {
                if (!(interface.flags() & QNetworkInterface::IsLoopBack) &&
                    (interface.flags() & QNetworkInterface::IsUp) &&
                    (interface.flags() & QNetworkInterface::IsRunning)) {
                    return interface;
                }
            }
            return QNetworkInterface(); // Invalid interface
        }
        

        as I said - x86_64 class works but Android class doesn't work. I guess this is android issue but i couldn't solve yet. last 1 week I focused this and i couldn't do anything. project is waiting this issue and we want to use Qt for Android. if we can't solve we will change qt to another frameworks. I really need help about this issue.

        Thanks for all helps!

        1 Reply Last reply
        0

        • Login

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