Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QT Networking Issue - Connection Refused



  • Hey All,

    I've just started writing my own little chat program between myself and someone about 300km away! (Yeah I could probably download one from the net, but where's the fun in that!?)

    I found some code on the net to get me started here is my mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
    	QMainWindow(parent),
    	ui(new Ui::MainWindow)
    {
    	ui->setupUi(this);
    
    	m_pTcpSocket = nullptr;
    }
    
    MainWindow::~MainWindow()
    {
    	delete ui;
    
    	m_pTcpServer = new QTcpServer(this);
    
    	connect(m_pTcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));
    	connect(m_pTcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
    
    	m_pTcpServer->listen(QHostAddress::Any, 772);
    }
    
    void MainWindow::on_connect_clicked()
    {
    	connectToHost( "127.0.0.1", 772 );
    }
    
    void MainWindow::connectToHost(QString hostname, quint16 port)
    {
    	if(!m_pTcpSocket)
    	{
    		m_pTcpSocket = new QTcpSocket(this);
    		m_pTcpSocket->setSocketOption(QAbstractSocket::KeepAliveOption,1);
    	}
    
    	connect(m_pTcpSocket,SIGNAL(readyRead()),SLOT(readSocketData()),Qt::UniqueConnection);
    	connect(m_pTcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),SLOT(connectionError(QAbstractSocket::SocketError)),Qt::UniqueConnection);
    	connect(m_pTcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),SLOT(tcpSocketState(QAbstractSocket::SocketState)),Qt::UniqueConnection);
    	connect(m_pTcpSocket,SIGNAL(disconnected()),SLOT(onConnectionTerminated()),Qt::UniqueConnection);
    	connect(m_pTcpSocket,SIGNAL(connected()),SLOT(onConnectionEstablished()),Qt::UniqueConnection);
    
    	if(!(QAbstractSocket::ConnectedState == m_pTcpSocket->state()))
    	{
    		m_pTcpSocket->connectToHost(hostname, port, QIODevice::ReadWrite, QAbstractSocket::AnyIPProtocol);
    	}
    }
    
    void MainWindow::sendMessage(QString msgToSend)
    {
    	QByteArray l_vDataToBeSent;
    	QDataStream l_vStream(&l_vDataToBeSent, QIODevice::WriteOnly);
    	l_vStream.setByteOrder(QDataStream::LittleEndian);
    	l_vStream << msgToSend.length();
    	l_vDataToBeSent.append(msgToSend);
    
    	m_pTcpSocket->write(l_vDataToBeSent, l_vDataToBeSent.length());
    }
    
    void MainWindow::readSocketData()
    {
    	while(m_pTcpSocket->bytesAvailable())
    	{
    		QByteArray receivedData = m_pTcpSocket->readAll();
    
    		qDebug() << receivedData;
    	}
    }
    
    void MainWindow::connectionError( QAbstractSocket::SocketError error )
    {
    	qDebug() << "CONNECTION_ERROR_SQ: " << error;
    }
    
    void MainWindow::tcpSocketState( QAbstractSocket::SocketState error )
    {
    	qDebug() << "CONNECTION_STATE_SQ: " << error;
    }
    
    void MainWindow::onConnectionTerminated()
    {
    	qDebug() << "Connection terminated";
    }
    
    void MainWindow::onConnectionEstablished()
    {
    	qDebug() << "Connection established";
    }
    
    void MainWindow::on_sendMessage_clicked()
    {
    	// Implement a send message here
    }
    
    void MainWindow::newConnection()
    {
    	 QTcpSocket *socket = m_pTcpServer->nextPendingConnection();
    
    	 qDebug() << "CONNECTION INCOMING...";
    }
    
    void MainWindow::serverError(QAbstractSocket::SocketError error)
    {
    	 qDebug() << "CONNECTION Error: " << error;
    }
    
    

    and my mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include <QAbstractSocket>
    #include <QtNetwork>
    #include <QTcpServer>
    #include <QTcpSocket>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
    	Q_OBJECT
    
    public:
    	explicit MainWindow(QWidget *parent = nullptr);
    	~MainWindow();
    
    private slots:
    	void on_connect_clicked();
    	void readSocketData();
    	void connectionError( QAbstractSocket::SocketError error );
    	void tcpSocketState( QAbstractSocket::SocketState error );
    	void onConnectionEstablished();
    	void onConnectionTerminated();
    	void newConnection();
    	void on_sendMessage_clicked();
    	void serverError(QAbstractSocket::SocketError error);
    
    private:
    	Ui::MainWindow *ui;
    
    	QTcpSocket*   m_pTcpSocket;
    	QTcpServer*   m_pTcpServer;
    	void connectToHost(QString hostname, quint16 port);
    	void sendMessage(QString msgToSend);
    };
    
    #endif // MAINWINDOW_H
    
    

    When I run the program and click on my connect button I get the following output:

    CONNECTION_STATE_SQ:  QAbstractSocket::HostLookupState
    CONNECTION_STATE_SQ:  QAbstractSocket::ConnectingState
    CONNECTION_STATE_SQ:  QAbstractSocket::UnconnectedState
    CONNECTION_ERROR_SQ:  QAbstractSocket::ConnectionRefusedError
    

    Could anyone please tell me why I am get a refused connection?

    I've disabled the firewall and tried localhost, 127.0.0.1 and my static ip, none work.

    I'm new to the Network side of things, so any help would be greatly appreciated.

    Thanks so much!

    Steve Q. :-)



  • Hello @steveq and welcome to Qt Forum.

    I readed your code and noticed that you have tried to create the server on destruction function of your MainWindow class:

    MainWindow::~MainWindow()
    {
       delete ui;
    
       m_pTcpServer = new QTcpServer(this);
    
       connect(m_pTcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));
       connect(m_pTcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
    
       m_pTcpServer->listen(QHostAddress::Any, 772);
    }
    

    A destructor function is called when the object goes out of scope or is deleted in one part of your code.

    If you are trying to create a QTcpServer Object when your MainWindow Class is inicializated, you should to write the code on Constructor Function as below code.

    MainWindow::MainWindow(QWidget *parent) :
    	QMainWindow(parent),
    	ui(new Ui::MainWindow)
    {
    	ui->setupUi(this);
    
    	m_pTcpSocket = nullptr;
           // create TCpServer Object
    	m_pTcpServer = new QTcpServer(this);
    
    	connect(m_pTcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));
    	connect(m_pTcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(serverError(QAbstractSocket::SocketError)));
    
    	m_pTcpServer->listen(QHostAddress::Any, 772);
    }
    
    MainWindow::~MainWindow()
    {
    	delete ui;
    }
    

    Btw, It is so necessary to know a bit about the Port Range.
    The port number is a number around 0 and 65535. However, the range from 0 to 1023 are the well-known ports or system ports.

    80 -> Http
    443 -> Https
    53 -> Dns

    Notice, if you try to listen on Port 772 as your code and use the isListening function to test, you will noticed that your server is not listening.

    It is because the QTcpServer will refuse all port below 1024. Thus, i suggest you to choose a port above 1023 to create your server.



  • @KillerSmath OMG how did I not see this. I feel like an idiot!!

    All working now.

    Thanks for you tip regarding the port range, I didn't know that QTcpServer would reject any ports below 1024.

    Thanks so much for your help. Sometimes you just need a second pair of eyes!!

    SQ :-)



  • @steveq
    It is okay :)
    If the problem has been solved, set this post to solved


  • Lifetime Qt Champion

    @steveq

    Thanks for you tip regarding the port range, I didn't know that QTcpServer would reject any ports below 1024.

    Thats not QTcpServer, but your operating system. You need elevated rights for ports < 1024.

    Regards


Log in to reply