Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Solved How do I know that the client has connected to the server?

    General and Desktop
    5
    21
    737
    Loading More Posts
    • 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.
    • N
      NintyS last edited by NintyS

      Hello I have a problem, Hi don't know when client connect to server. ( I am a accustomed to SFML network and Qt network is a little bit hard to me ). Here is code: https://github.com/NintyS/NetworkInQt. ( 5.15.2 )

      1 Reply Last reply Reply Quote 0
      • Christian Ehrlicher
        Christian Ehrlicher Lifetime Qt Champion last edited by

        This is working fine for me:

        #include <QtNetwork>
        
        int main(int argc, char* argv[])
        {
            QCoreApplication app(argc, argv);
            
            QTcpServer server;
            if (!server.listen(QHostAddress::Any, 50153))
                return 1;
            QObject::connect(&server, &QTcpServer::newConnection,
                             &server, [&server]() {
                QTcpSocket *socket = server.nextPendingConnection();
                qDebug() << "client connected from" << socket->peerAddress() << ":" << socket->peerPort();
                socket->write("Test\n");
                socket->flush();
                socket->waitForBytesWritten(300);
                socket->close();
            });
            
            QTcpSocket client;
            QObject::connect(&client, &QTcpSocket::readyRead,
                             &client, [&client]() {
                qDebug() << client.readAll();
                QCoreApplication::quit();
            });
            client.connectToHost("localhost", 50153);
            
            return app.exec();
        }
        
        

        Qt has to stay free or it will die.

        JonB 1 Reply Last reply Reply Quote 2
        • Christian Ehrlicher
          Christian Ehrlicher Lifetime Qt Champion last edited by

          The QTcpServer will emit the signal newConnection()

          Qt has to stay free or it will die.

          1 Reply Last reply Reply Quote 0
          • N
            NintyS last edited by

            I know and I used this but void in connect don't start.

            1 Reply Last reply Reply Quote 0
            • Christian Ehrlicher
              Christian Ehrlicher Lifetime Qt Champion last edited by

              @NintyS said in How do I know that the client has connected to the server?:

              but void in connect don't start.

              What does this mean? I don't understand.

              Qt has to stay free or it will die.

              1 Reply Last reply Reply Quote 0
              • N
                NintyS last edited by NintyS

                In Connect I use signal to active void newConnection. ( Or maybe I don't understand something )

                #include "server.hpp"
                
                server::server(QObject *parent) : QObject(parent) {
                    serverObject = new QTcpServer(this);
                
                    connect(serverObject, SIGNAL(newConnection()), this, SLOT(newConnection()));
                
                    if(serverObject->listen(QHostAddress::Any, 50153)) {
                        printf("Yes");
                    } else { printf("No"); }
                }
                
                void server::newConnection() {
                
                    printf("123");
                
                    QTcpSocket *socket = serverObject->nextPendingConnection();
                
                    socket->write("Test\n");
                    socket->flush();
                
                    socket->waitForBytesWritten(300);
                
                    socket->close();
                }
                

                ( I understand this that: if ( connect ) something ( signal ) then something ( slot )

                1 Reply Last reply Reply Quote 0
                • Christian Ehrlicher
                  Christian Ehrlicher Lifetime Qt Champion last edited by

                  And with which program do you connect to this port? Are you sure it really connects to your address?
                  And please use the new signal/slot syntax.

                  Qt has to stay free or it will die.

                  1 Reply Last reply Reply Quote 1
                  • N
                    NintyS last edited by

                    No, I'm not sure but when I close the program then I have a message "connected", so I thinking I connect with my server.

                    Christian Ehrlicher 1 Reply Last reply Reply Quote 0
                    • Christian Ehrlicher
                      Christian Ehrlicher Lifetime Qt Champion @NintyS last edited by

                      @NintyS said in How do I know that the client has connected to the server?:

                      No, I'm not sure but when I close the program then I have a message "connected", so I thinking I connect with my server.

                      Sorry but please be more precise. Why do you get a 'connected' when you close a program? This doesn't sounds very useful. What program is this? Please use a simple QTcpSocket as shown in the QTcpServer examples to check your program. Or try to connect with e.g. telnet to your listen port.

                      Qt has to stay free or it will die.

                      N 1 Reply Last reply Reply Quote 1
                      • N
                        NintyS last edited by

                        Now this is a simple program what must connect to server and close. I will be try on my own hand, if I do it, I will write about it.

                        1 Reply Last reply Reply Quote 0
                        • Christian Ehrlicher
                          Christian Ehrlicher Lifetime Qt Champion last edited by

                          This is working fine for me:

                          #include <QtNetwork>
                          
                          int main(int argc, char* argv[])
                          {
                              QCoreApplication app(argc, argv);
                              
                              QTcpServer server;
                              if (!server.listen(QHostAddress::Any, 50153))
                                  return 1;
                              QObject::connect(&server, &QTcpServer::newConnection,
                                               &server, [&server]() {
                                  QTcpSocket *socket = server.nextPendingConnection();
                                  qDebug() << "client connected from" << socket->peerAddress() << ":" << socket->peerPort();
                                  socket->write("Test\n");
                                  socket->flush();
                                  socket->waitForBytesWritten(300);
                                  socket->close();
                              });
                              
                              QTcpSocket client;
                              QObject::connect(&client, &QTcpSocket::readyRead,
                                               &client, [&client]() {
                                  qDebug() << client.readAll();
                                  QCoreApplication::quit();
                              });
                              client.connectToHost("localhost", 50153);
                              
                              return app.exec();
                          }
                          
                          

                          Qt has to stay free or it will die.

                          JonB 1 Reply Last reply Reply Quote 2
                          • N
                            NintyS last edited by

                            Thank you very much :D

                            1 Reply Last reply Reply Quote 0
                            • JonB
                              JonB @Christian Ehrlicher last edited by

                              @Christian-Ehrlicher said in How do I know that the client has connected to the server?:

                                  socket->flush();
                                  socket->waitForBytesWritten(300);
                              

                              Does one have to have these two lines prior to socket->close(), or are you just being "safe"?

                              1 Reply Last reply Reply Quote 0
                              • Christian Ehrlicher
                                Christian Ehrlicher Lifetime Qt Champion last edited by

                                The waitForBytesWritten() is needed.

                                Qt has to stay free or it will die.

                                KroMignon 1 Reply Last reply Reply Quote 1
                                • N
                                  NintyS @Christian Ehrlicher last edited by

                                  @Christian-Ehrlicher I know now why. I use a printf() to show the result. Now when I use qDebug I see my result after connection.

                                  JonB 1 Reply Last reply Reply Quote 0
                                  • JonB
                                    JonB @NintyS last edited by JonB

                                    @NintyS
                                    printf() is liable to be at least line-buffered, maybe even fully buffered. You would have to follow it with fflush(stdout) to try to see the output immediately. fprintf(stderr, ...) would probably be better. In any case qDebug() is a better choice for debugging.

                                    1 Reply Last reply Reply Quote 0
                                    • KroMignon
                                      KroMignon @Christian Ehrlicher last edited by

                                      @Christian-Ehrlicher said in How do I know that the client has connected to the server?:

                                      the waitForBytesWritten() is needed.

                                      Why? My understanding was that waitForBytesWritten() is only required if not event queue is available... But without event queue, the connect() won't work.

                                      It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

                                      Christian Ehrlicher J.Hilk 2 Replies Last reply Reply Quote 0
                                      • Christian Ehrlicher
                                        Christian Ehrlicher Lifetime Qt Champion @KroMignon last edited by

                                        @KroMignon Because of the close() directly afterwards. I'm pretty sure close() will call flush() before but it's not documented.

                                        Qt has to stay free or it will die.

                                        1 Reply Last reply Reply Quote 1
                                        • J.Hilk
                                          J.Hilk Moderators @KroMignon last edited by

                                          @KroMignon probably because of the immediate call to close on the socket

                                          you could alternatively, potentially nest lambdas

                                                 QTcpSocket *socket = server.nextPendingConnection();
                                                      qDebug() << "client connected from" << socket->peerAddress() << ":" << socket->peerPort();
                                                      QByteArray data{"Test\n"};
                                                      QObject::connect(socket, &QTcpSocket::bytesWritten, socket, [socket, bytesToSend = data.size()](qint64 bytes)->void{
                                                          static qint64 bytesSend{0};
                                                          bytesSend += bytes;
                                                          if(static_cast<qint64>(bytesToSend) == bytesSend)
                                                              socket->close();
                                                      });
                                                      socket->write(data);
                                                  });
                                          

                                          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct

                                          Qt Needs YOUR vote: https://bugreports.qt.io/browse/QTQAINFRA-4121


                                          Q: What's that?
                                          A: It's blue light.
                                          Q: What does it do?
                                          A: It turns blue.

                                          KroMignon JonB 2 Replies Last reply Reply Quote 1
                                          • KroMignon
                                            KroMignon @J.Hilk last edited by

                                            @J-Hilk said in How do I know that the client has connected to the server?:

                                            you could alternatively, potentially nest lambdas

                                                   QTcpSocket *socket = server.nextPendingConnection();
                                                        qDebug() << "client connected from" << socket->peerAddress() << ":" << socket->peerPort();
                                                        QByteArray data{"Test\n"};
                                                        QObject::connect(socket, &QTcpSocket::bytesWritten, socket, [socket, bytesToSend = data.size()](qint64 bytes)->void{
                                                            static qint64 bytesSend{0};
                                                            bytesSend += bytes;
                                                            if(static_cast<qint64>(bytesToSend) == bytesSend)
                                                                socket->close();
                                                        });
                                                        socket->write(data);
                                                    });
                                            

                                            Hmm, I would do it like this:

                                            QTcpSocket *socket = server.nextPendingConnection();
                                            qDebug() << "client connected from" << socket->peerAddress() << ":" << socket->peerPort();
                                            QByteArray data{"Test\n"};
                                            QObject::connect(socket, &QTcpSocket::bytesWritten, socket, [socket](qint64 bytes)->void{
                                                if(socket->bytesToWrite() == 0)
                                                    socket->close();
                                            });
                                            socket->write(data);
                                            

                                            It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

                                            J.Hilk 1 Reply Last reply Reply Quote 0
                                            • J.Hilk
                                              J.Hilk Moderators @KroMignon last edited by

                                              @KroMignon potentially, I'm not familiar enough with the inner workings of QAbstractSocket to say for sure, that bytesToWrite is updated before bytesWritten is emitted 🤷‍♂️

                                              Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct

                                              Qt Needs YOUR vote: https://bugreports.qt.io/browse/QTQAINFRA-4121


                                              Q: What's that?
                                              A: It's blue light.
                                              Q: What does it do?
                                              A: It turns blue.

                                              1 Reply Last reply Reply Quote 0
                                              • First post
                                                Last post