c++qtqtcpsocketqtcpserver

Qt C++ unable to connect to QTcpServer using Telnet


I have watched VoidRealm's Youtube video, C++ Qt 67 - QTCPServer - a basic TCP server application and followed his instructions, however, I can't connect to the QTcpServer I created using Telnet.

My Code:

//myserver.h

#ifndef MYSERVER_H
#define MYSERVER_H

#include <QObject>
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>

class MyServer : public QObject
{
    Q_OBJECT
public:
    explicit MyServer(QObject *parent = nullptr);

    void newConnection();
signals:

private:
    QTcpServer *server;
};
#endif // MYSERVER_H

//myserver.cpp

#include "myserver.h"

MyServer::MyServer(QObject *parent)
    : QObject{parent}
{
    server = new QTcpServer(this);

    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));

    if(!server->listen(QHostAddress::Any, 1234))
    {
        qDebug() << "Server could not start!";
    }else{
        qDebug() << "Server started!";
    }
}

void MyServer::newConnection()
{
    QTcpSocket *socket = server->nextPendingConnection();

    socket->write("hello client\r\n");
    socket->flush();

    socket->waitForBytesWritten(3000);

    socket->close();
}

Running this code, in the Console screen I get

qt.core.qobject.connect: QObject::connect: No such slot MyServer::newConnection() in ..\First_Server\myserver.cpp:8
Server started!

but when I open a command prompt and do the following steps:

...>telnet
Welcome to Microsoft Telnet Client

Escape Character is 'CTRL+]'

Microsoft Telnet> open 127.0.0.1 1234
Connecting To 127.0.0.1...

It is not connecting. Can anyone tell me what I have done wrong? I am using Qt 6.3.0.


Solution

  • You error message indicates the issue:

    qt.core.qobject.connect: QObject::connect: No such slot MyServer::newConnection() in ..\First_Server\myserver.cpp:8 Server started!

    You have created the connection between the signal and slot here.

    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
    

    First of all, it is not a good idea to have the same slot name as the signal as it becomes confusing. I would call your slot as "handleNewConnection" for example. Secondly, you ought to use the "new" signal-slot syntax. Thirdly, and most importantly, you have not declared your newConnection() method to be a slot. You would need to declare it so in your header file:

    private Q_SLOTS:
        void newConnection();
    

    You can also make the slots public if it has to be accessed from outside, it looks like that you would only use it privately here.