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. QT Networking Issue - Connection Refused
Forum Updated to NodeBB v4.3 + New Features

QT Networking Issue - Connection Refused

Scheduled Pinned Locked Moved Solved General and Desktop
5 Posts 3 Posters 2.3k 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.
  • S Offline
    S Offline
    steveq
    wrote on 19 Apr 2019, 02:54 last edited by
    #1

    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. :-)

    K 1 Reply Last reply 19 Apr 2019, 03:54
    0
    • S steveq
      19 Apr 2019, 02:54

      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. :-)

      K Offline
      K Offline
      KillerSmath
      wrote on 19 Apr 2019, 03:54 last edited by
      #2

      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.

      @Computer Science Student - Brazil
      Web Developer and Researcher
      “Sometimes it’s the people no one imagines anything of who do the things that no one can imagine.” - Alan Turing

      1 Reply Last reply
      4
      • S Offline
        S Offline
        steveq
        wrote on 19 Apr 2019, 04:14 last edited by
        #3

        @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 :-)

        K aha_1980A 2 Replies Last reply 19 Apr 2019, 04:17
        0
        • S steveq
          19 Apr 2019, 04:14

          @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 :-)

          K Offline
          K Offline
          KillerSmath
          wrote on 19 Apr 2019, 04:17 last edited by
          #4

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

          @Computer Science Student - Brazil
          Web Developer and Researcher
          “Sometimes it’s the people no one imagines anything of who do the things that no one can imagine.” - Alan Turing

          1 Reply Last reply
          1
          • S steveq
            19 Apr 2019, 04:14

            @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 :-)

            aha_1980A Offline
            aha_1980A Offline
            aha_1980
            Lifetime Qt Champion
            wrote on 19 Apr 2019, 05:33 last edited by
            #5

            @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

            Qt has to stay free or it will die.

            1 Reply Last reply
            3

            1/5

            19 Apr 2019, 02:54

            • Login

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