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. Send Custom class object using QtcpSocket and QtcpServer
Forum Updated to NodeBB v4.3 + New Features

Send Custom class object using QtcpSocket and QtcpServer

Scheduled Pinned Locked Moved Solved General and Desktop
6 Posts 3 Posters 1.2k 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.
  • AnmolA Offline
    AnmolA Offline
    Anmol
    wrote on last edited by
    #1

    i am creating a network system. i know how to send text over network but i need to send my Custom class object over network. how can i send a object over TCP network.

    1 Reply Last reply
    0
    • Christian EhrlicherC Offline
      Christian EhrlicherC Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote on last edited by
      #2

      You need to serialize your class and deserialize it on the other side. You can use QDataStream for this or write it by your own.

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      AnmolA 1 Reply Last reply
      4
      • Christian EhrlicherC Christian Ehrlicher

        You need to serialize your class and deserialize it on the other side. You can use QDataStream for this or write it by your own.

        AnmolA Offline
        AnmolA Offline
        Anmol
        wrote on last edited by Anmol
        #3

        @Christian-Ehrlicher

        deserialize not working. after deserialize getName() [ myserver.cpp -- readredy() ] returns empty string

        my entire test project : https://github.com/Anmol-A-jain/test.git

        i'm trying to send Data class over network.
        data.h

        #ifndef DATA_H
        #define DATA_H
        
        #include <QtCore>
        
        class Data
        {
        public:
            Data();
            void setName(QString name);
            QString getName();
        private:
            QString Name;
        };
        
        #endif // DATA_H
        
        

        data.cpp

        #include "data.h"
        
        Data::Data()
        {
            this->Name = "null";
        }
        
        void Data::setName(QString name)
        {
            this->Name = name;
        }
        
        QString Data::getName()
        {
            return this->Name;
        }
        

        client:
        main.cpp

        #include <QCoreApplication>
        #include <QTcpSocket>
        #include <QDataStream>
        #include <QDebug>
        #include "data.h"
        
        int main(int argc, char *argv[])
        {
            QCoreApplication a(argc, argv);
        
            QTcpSocket* client = new QTcpSocket;
        
            client->connectToHost("127.0.0.1", 5555);
        
            Data d;
            d.setName("Anmol");
        
            QByteArray byte;
            qDebug() << "d String :" << d.getName();
            QDataStream data(&byte,QIODevice::WriteOnly);
            data.writeRawData(reinterpret_cast<const char*>(&d),sizeof(d));
        
            qDebug() << byte;
        
            client->write(byte);
        
            return a.exec();
        }
        

        server :
        myserver.h

        #ifndef MYSERVER_H
        #define MYSERVER_H
        
        #include <QObject>
        #include <QTcpServer>
        #include <QTcpSocket>
        #include <QDebug>
        
        class myServer : public QObject
        {
            Q_OBJECT
        private:
            QTcpServer* server;
        
        public:
            explicit myServer(QObject *parent = nullptr);
        
        signals:
        
        public slots:
            void newConnection();
            void readredy();
        };
        
        #endif // MYSERVER_H
        
        

        myserver.cpp

        #include "myserver.h"
        #include "data.h"
        
        myServer::myServer(QObject *parent) : QObject(parent)
        {
            server = new QTcpServer();
            clientList = new QVector<QTcpSocket*>();
        
            connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
        
            if(server->listen(QHostAddress::Any,5555) )
            {
                qDebug() << "connection started" << endl;
            }
            else
            {
                qDebug() << "connection not started" << endl;
            }
        }
        
        void myServer::newConnection()
        {
            QTcpSocket *client = server->nextPendingConnection();
            connect(client,&QTcpSocket::readyRead,this,&myServer::readredy );
        }
        
        void myServer::readredy()
        {
            QTcpSocket *client = static_cast<QTcpSocket *>(QObject::sender());
            QByteArray byte = client->readAll();
        
            QDataStream read(&byte,QIODevice::ReadOnly);
            Data d1 ;
            qDebug() << "d1 String before deserialize :" << d1.getName();
        
            read.readRawData(reinterpret_cast<char*>(&d1),sizeof(d1));
            qDebug() << "d1 String after deserialize :" << d1.getName();
        
            qDebug() << "Message: " + d1.getName() ;
        
            delete client;
        
        }
        

        main.cpp

        #include <QCoreApplication>
        #include "myserver.h"
        
        int main(int argc, char *argv[])
        {
            QCoreApplication a(argc, argv);
        
            myServer s;
        
            return a.exec();
        }
        

        Error picture :
        left one is Client app and right one is Server app:
        Screenshot (9).png

        kshegunovK 1 Reply Last reply
        0
        • Christian EhrlicherC Offline
          Christian EhrlicherC Offline
          Christian Ehrlicher
          Lifetime Qt Champion
          wrote on last edited by
          #4

          Please take a look at the QDataStream documentation - you can't simply copy the (expected) Memory of your class - you have to (de)serialize your members of the class with the help of QDataStream.

          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
          Visit the Qt Academy at https://academy.qt.io/catalog

          1 Reply Last reply
          4
          • AnmolA Anmol

            @Christian-Ehrlicher

            deserialize not working. after deserialize getName() [ myserver.cpp -- readredy() ] returns empty string

            my entire test project : https://github.com/Anmol-A-jain/test.git

            i'm trying to send Data class over network.
            data.h

            #ifndef DATA_H
            #define DATA_H
            
            #include <QtCore>
            
            class Data
            {
            public:
                Data();
                void setName(QString name);
                QString getName();
            private:
                QString Name;
            };
            
            #endif // DATA_H
            
            

            data.cpp

            #include "data.h"
            
            Data::Data()
            {
                this->Name = "null";
            }
            
            void Data::setName(QString name)
            {
                this->Name = name;
            }
            
            QString Data::getName()
            {
                return this->Name;
            }
            

            client:
            main.cpp

            #include <QCoreApplication>
            #include <QTcpSocket>
            #include <QDataStream>
            #include <QDebug>
            #include "data.h"
            
            int main(int argc, char *argv[])
            {
                QCoreApplication a(argc, argv);
            
                QTcpSocket* client = new QTcpSocket;
            
                client->connectToHost("127.0.0.1", 5555);
            
                Data d;
                d.setName("Anmol");
            
                QByteArray byte;
                qDebug() << "d String :" << d.getName();
                QDataStream data(&byte,QIODevice::WriteOnly);
                data.writeRawData(reinterpret_cast<const char*>(&d),sizeof(d));
            
                qDebug() << byte;
            
                client->write(byte);
            
                return a.exec();
            }
            

            server :
            myserver.h

            #ifndef MYSERVER_H
            #define MYSERVER_H
            
            #include <QObject>
            #include <QTcpServer>
            #include <QTcpSocket>
            #include <QDebug>
            
            class myServer : public QObject
            {
                Q_OBJECT
            private:
                QTcpServer* server;
            
            public:
                explicit myServer(QObject *parent = nullptr);
            
            signals:
            
            public slots:
                void newConnection();
                void readredy();
            };
            
            #endif // MYSERVER_H
            
            

            myserver.cpp

            #include "myserver.h"
            #include "data.h"
            
            myServer::myServer(QObject *parent) : QObject(parent)
            {
                server = new QTcpServer();
                clientList = new QVector<QTcpSocket*>();
            
                connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
            
                if(server->listen(QHostAddress::Any,5555) )
                {
                    qDebug() << "connection started" << endl;
                }
                else
                {
                    qDebug() << "connection not started" << endl;
                }
            }
            
            void myServer::newConnection()
            {
                QTcpSocket *client = server->nextPendingConnection();
                connect(client,&QTcpSocket::readyRead,this,&myServer::readredy );
            }
            
            void myServer::readredy()
            {
                QTcpSocket *client = static_cast<QTcpSocket *>(QObject::sender());
                QByteArray byte = client->readAll();
            
                QDataStream read(&byte,QIODevice::ReadOnly);
                Data d1 ;
                qDebug() << "d1 String before deserialize :" << d1.getName();
            
                read.readRawData(reinterpret_cast<char*>(&d1),sizeof(d1));
                qDebug() << "d1 String after deserialize :" << d1.getName();
            
                qDebug() << "Message: " + d1.getName() ;
            
                delete client;
            
            }
            

            main.cpp

            #include <QCoreApplication>
            #include "myserver.h"
            
            int main(int argc, char *argv[])
            {
                QCoreApplication a(argc, argv);
            
                myServer s;
            
                return a.exec();
            }
            

            Error picture :
            left one is Client app and right one is Server app:
            Screenshot (9).png

            kshegunovK Offline
            kshegunovK Offline
            kshegunov
            Moderators
            wrote on last edited by
            #5

            @Anmol said in Send Custom class object using QtcpSocket and QtcpServer:

            deserialize not working. after deserialize getName() [ myserver.cpp -- readredy() ] returns empty string

            Your code is wrong.
            You've written a memory address and then expect to read that memory address on the other side? It's not going to work like that. It's a small wonder it doesn't simply crash. Don't be lazy, write a couple of functions and serialize the data properly, which incidentally means: don't use reinterpret_cast, especially when you're not 100% sure what it does.

            Read and abide by the Qt Code of Conduct

            1 Reply Last reply
            5
            • AnmolA Offline
              AnmolA Offline
              Anmol
              wrote on last edited by
              #6

              i have created a method for writing all data into QByteArray and send it and then reading data from it at other side. its works perfectly.

              Thanks for helping me.

              1 Reply Last reply
              3

              • Login

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