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. Client , Server communication
Forum Updated to NodeBB v4.3 + New Features

Client , Server communication

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

    Hi , I created client and server .
    The connection established and data transmitted from client to server , when I try send message from server to client the client prints empty quotes here is the client side communication handle :

    • Server on ubuntu VMware behind VMware's NAT, tested on bridged connection too.
    • Checked on Wireshark the data transmitted
    • Sent data independently ( without conditions ) and got same result
    • Sent data from main using socket I created under sync function same result

    Here is the output :

    sync request sent.
    Data received from server.
    Raw Data: ""
    Data :  ""
    stringed data :  ""
    
    #include "client.h"
    #include <QTimer>
    
    Client::Client(QObject *parent) : QObject(parent)
    {
        socket = new QTcpSocket(this);
        connect(socket, &QTcpSocket::disconnected, this, &Client::disconnect);
    }
    
    void Client::syncApplication()
    {
        qDebug() << "sync request sent.";
        
        socket->connectToHost("192.168.242.128", 12345); // server's IP and port
    
        if (socket->waitForConnected())
        {
            // Send the "sync" signal
            socket->write("connected");
            socket->flush(); // Flush the data to ensure it's sent immediately
        }
    
        else
        {
            // Handle connection error
            qDebug() << "Error: " << socket->errorString();
        }
    }
    
    void Client::DataReceived()
    {
        qDebug() << "Data received from server.";
    
        // Read incoming data
        QByteArray data = socket->readAll();
    
        qDebug() << "Raw Data:" << data.toHex();
    
        qDebug() << "Data : " << data;
    
        // Convert data to string for comparison
        QString message = QString::fromUtf8(data);
    
        qDebug() << "stringed data : " << message;
    
        // Handle heartbeat message
        if (message == "heartbeat")
        {
            qDebug() << "Received heartbeat from server.";
            // Start sending heartbeat messages again
            sendHeartbeat();
        }
    
        else if (message =="Connected")
        {
            qDebug() << "acknowledged.";
    
        }
    }
    
    Here is server code:
    
    
            ```
    connected_clients[client_socket_fd].last_heartbeat_time = time(nullptr);
    
            // Handle received data
            buffer[bytes_received] = '\0';
            std::cout << "Received message from " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port) << ": " << buffer << std::endl;
    
    
            // Send Hello message to the client
            const char* message = "Hello, Client!\n";
            int result = send(client_socket_fd, message, strlen(message), 0);
            std::cout << "Hello message sent to client." << std::endl;
    
            // Respond to heartbeat
            if (strcmp(buffer, "heartbeat") == 0) {
                send(client_socket_fd, "heartbeat", strlen("heartbeat"), 0);
            }
            else if (strcmp(buffer, "connected") == 0) {
                send(client_socket_fd, "heartbeat", strlen("heartbeat"), 0);
                std::cout << "Received message connected  " << std::endl;
                std::cout << "Sent message 'heartbeat' to client" << std::endl;
            }
        }
    
        // Remove client from connected_clients map
        close(client_socket_fd);
        connected_clients.erase(client_socket_fd);
    }
    
    int main() {
        // Create a TCP socket
        int server_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (server_socket_fd < 0) {
            std::cerr << "Error creating socket." << std::endl;
            return 1;
        }
    
        // Bind the socket to the address and port
        struct sockaddr_in server_addr;
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = inet_addr(SERVER_HOST);
        server_addr.sin_port = htons(SERVER_PORT);
        if (bind(server_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
            std::cerr << "Error binding socket." << std::endl;
            return 1;
        }
    
        // Listen for incoming connections
        if (listen(server_socket_fd, 5) < 0) {
            std::cerr << "Error listening on socket." << std::endl;
            return 1;
        }
    
        std::cout << "Server is listening on " << SERVER_HOST << ":" << SERVER_PORT << std::endl;
    
        // Main loop to accept incoming connections
        while (true) {
            // Accept a new connection
            struct sockaddr_in client_addr;
            socklen_t client_addr_len = sizeof(client_addr);
            int client_socket_fd = accept(server_socket_fd, (struct sockaddr*)&client_addr, &client_addr_len);
            if (client_socket_fd < 0) {
                std::cerr << "Error accepting connection." << std::endl;
                continue;
            }
    
            // Create a new thread to handle the client connection
            std::thread client_thread(handle_client_connection, client_socket_fd, client_addr);
            client_thread.detach();  // Detach the thread to allow it to run independently
        }
    
        // Close the server socket
        close(server_socket_fd);
    
        return 0;
    }
    
    1 Reply Last reply
    0
    • _ __d4ve__

      @JonB
      something like that ?

      Client::Client(QObject *parent) : QObject(parent)
      {
          socket = new QTcpSocket(this);
          connect(socket, &QTcpSocket::readyRead, this, &Client::onDataReceived);
      }
      

      I added sleep to the function but issue persists

      void TrayIconApp::syncApplication()
      {
          Client client;
      
          client.syncApplication();
          Sleep(3000);
          client.DataReceived();
      }
      
      _ Offline
      _ Offline
      __d4ve__
      wrote on last edited by
      #6

      @__d4ve__

      I used socket->bytesAvailable() and it seems to solve the problem.

      1 Reply Last reply
      0
      • C Offline
        C Offline
        ChrisW67
        wrote on last edited by
        #2

        @__d4ve__ You have not connected anything to Client::DataReceived() so it is hard to see how anything at all is output.

        You might find this post from not too long ago useful. Handles multiple clients without threading muddying the waters.

        _ 1 Reply Last reply
        1
        • C ChrisW67

          @__d4ve__ You have not connected anything to Client::DataReceived() so it is hard to see how anything at all is output.

          You might find this post from not too long ago useful. Handles multiple clients without threading muddying the waters.

          _ Offline
          _ Offline
          __d4ve__
          wrote on last edited by
          #3

          @ChrisW67

          • Both functions are objects of Client that's running under same function

          • regrading your advice looking in the post you mentioned , I find it not compatible mixing 'pure' C++ , though it possible.

          void TrayIconApp::syncApplication()
          {
              Client client;
              client.syncApplication();
              client.DataReceived();
          }
          
          • what makes the issue remain
          JonBJ 1 Reply Last reply
          0
          • _ __d4ve__

            @ChrisW67

            • Both functions are objects of Client that's running under same function

            • regrading your advice looking in the post you mentioned , I find it not compatible mixing 'pure' C++ , though it possible.

            void TrayIconApp::syncApplication()
            {
                Client client;
                client.syncApplication();
                client.DataReceived();
            }
            
            • what makes the issue remain
            JonBJ Offline
            JonBJ Offline
            JonB
            wrote on last edited by
            #4

            @__d4ve__
            It is hard to make out what you are saying.

            DataRecieved/socket->readAll(); needs to be called in a slot connected to socket's readyRead signal (and may be called more than once). You just call it once immediately after connecting to host/writing something. You data received could easily be empty, as per your output.

            _ 1 Reply Last reply
            0
            • JonBJ JonB

              @__d4ve__
              It is hard to make out what you are saying.

              DataRecieved/socket->readAll(); needs to be called in a slot connected to socket's readyRead signal (and may be called more than once). You just call it once immediately after connecting to host/writing something. You data received could easily be empty, as per your output.

              _ Offline
              _ Offline
              __d4ve__
              wrote on last edited by __d4ve__
              #5

              @JonB
              something like that ?

              Client::Client(QObject *parent) : QObject(parent)
              {
                  socket = new QTcpSocket(this);
                  connect(socket, &QTcpSocket::readyRead, this, &Client::onDataReceived);
              }
              

              I added sleep to the function but issue persists

              void TrayIconApp::syncApplication()
              {
                  Client client;
              
                  client.syncApplication();
                  Sleep(3000);
                  client.DataReceived();
              }
              
              _ 1 Reply Last reply
              0
              • _ __d4ve__

                @JonB
                something like that ?

                Client::Client(QObject *parent) : QObject(parent)
                {
                    socket = new QTcpSocket(this);
                    connect(socket, &QTcpSocket::readyRead, this, &Client::onDataReceived);
                }
                

                I added sleep to the function but issue persists

                void TrayIconApp::syncApplication()
                {
                    Client client;
                
                    client.syncApplication();
                    Sleep(3000);
                    client.DataReceived();
                }
                
                _ Offline
                _ Offline
                __d4ve__
                wrote on last edited by
                #6

                @__d4ve__

                I used socket->bytesAvailable() and it seems to solve the problem.

                1 Reply Last reply
                0
                • _ __d4ve__ has marked this topic as solved on

                • Login

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