QObject: no such slot QThread::readyRead() - c++

I am trying to figure out how to correctly use Qt TCP Sockets, as well as multithreading. I want, as a test project in support of something more complex but similar I will try in the future, to do the following: a simple application that either listens for exactly one incoming connection, or connects to a serversocket; next it prints everything it receives over that socket.
The situation where I connect to a serversocket (I use netcat with the -l option for this) works fine: everything netcat sends to my application is printed correctly. However, when I use my program to listen for that one incoming connection (generated by netcat), the connecting succeeds but then I get this runtime error:
QObject::connect: No such signal QThread::readyRead() in ..\QTcpTest\listener.cpp:8
Here is the entire code (don't mind the plain C I/O I use sometimes, I'll remove this later):
[ main.cpp ]
#include "peer.h"
#include <QCoreApplication>
#include <QThread>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static bool askIfServer();
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Peer *p;
int rval;
if (askIfServer())
p = new Peer;
else
p = new Peer(false);
rval = a.exec();
delete p;
return rval;
}
static bool askIfServer()
{
bool isServer;
char ibuf[BUFSIZ];
fputs("Choose \'host\' or \'join\': ", stderr);
fgets(ibuf, BUFSIZ, stdin);
ibuf[strlen(ibuf) - 1] = '\0';
fflush(stdin);
if (strcmp(ibuf, "host") == 0)
isServer = true;
else if (strcmp(ibuf, "join") == 0)
isServer = false;
else
{
fputs("Failure.\n", stderr);
exit(-1);
}
return isServer;
}
[ peer.h ]
#ifndef PEER_H
#define PEER_H
#include "listener.h"
#include <QObject>
#include <QThread>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
class Peer : public QObject
{
Q_OBJECT
public:
static const quint16 PORT = 5483;
explicit Peer(bool isHost = true, QString hostname = "localhost", QObject *parent = 0);
public slots:
void acceptPeer();
private:
bool _isHost;
QTcpServer *_server;
QTcpSocket *_socket;
QThread *_lThread;
Listener *_listener;
};
#endif // PEER_H
[ peer.cpp ]
#include "peer.h"
Peer::Peer(bool isHost, QString hostname, QObject *parent) :
QObject(parent),
_isHost(isHost)
{
if (_isHost)
{
_server = new QTcpServer;
connect(_server, SIGNAL(newConnection()), this, SLOT(acceptPeer()));
_server->listen(QHostAddress::Any, PORT);
}
else
{
_socket = new QTcpSocket;
connect(_socket, SIGNAL(hostFound()), this, SLOT(acceptPeer()));
_socket->connectToHost(hostname, PORT);
}
}
void Peer::acceptPeer()
{
disconnect(this, SLOT(acceptPeer()));
if (_isHost)
{
_socket = _server->nextPendingConnection();
delete _server;
_server = NULL;
}
_lThread = new QThread;
_listener = new Listener(_socket);
_listener->moveToThread(_lThread);
_lThread->start();
}
[ listener.h ]
#ifndef LISTENER_H
#define LISTENER_H
#include <iostream>
#include <QObject>
#include <QByteArray>
#include <QtNetwork/QTcpSocket>
using std::cout;
class Listener : public QObject
{
Q_OBJECT
public:
explicit Listener(QTcpSocket *socket, QObject *parent = 0);
public slots:
void acceptData();
private:
QTcpSocket *_socket;
};
#endif // LISTENER_H
[ listener.cpp ]
#include "listener.h"
Listener::Listener(QTcpSocket *socket, QObject *parent) :
QObject(parent),
_socket(socket)
{
// I guess this is where it goes wrong
connect(_socket, SIGNAL(readyRead()), this, SLOT(acceptData()), Qt::QueuedConnection);
}
void Listener::acceptData()
{
QByteArray data = _socket->readAll();
cout << data.constData();
}
The thing I do not get is that the error message claims that I try to connect some signal from QThread (and I clearly do not: see listener.cpp:8); even stranger is that this only happens when the socket is created by the QTcpServer instance, not in the other case. What am I missing?
EDIT: SOLVED
See my own answer.

I do not use an extra thread anymore (see comment). The problem was deleting the QTcpServer instance in Peer::acceptPeer(), once a connection was established. I thought that I could delete it because I only need that one socket QTcpServer::nextPendingConnection() returns. Apparently this is wrong, the socket is probably destroyed as well, leaving me with a rogue pointer (I think) crashing the program. Now I only call _server->pauseAccepting(); right after I get the socket, and all works fine.
Here is the change I've made:
void Peer::acceptPeer()
{
disconnect(this, SLOT(acceptPeer()));
if (_isHost)
{
_socket = _server->nextPendingConnection();
_server->pauseAccepting(); // no deletion
}
_listener = new Listener(_socket);
}

Related

How to check if keyboard is connected or or not and use it if it is connected during runtime?

So I have a QT project in which I want to check if a keyboard is connected. In case it's not connected I want to be able to still use it if it is connected during the program is running. I looked around and found a few libraries that might be suitable but I am not sure if they can do what I want. Libraries in question: libinput, libusb or Solid with KDE. My question is, will one of these libraries do what I want it to do or is it something completly different? If it is one of the above libraries than any examples would help a ton because I can't really get anything out of the documentation. I should probably also mention that I use a linux, or to be more exact openSUSE Leap 15.2
Okay, well turns out it wasn't as complicated as I thought and none of the libraries that I talked about are needed. Here is my solution, in case any one in the future is looking for something similar.
scanner.h
#ifndef SCANNER_H
#define SCANNER_H
#include <QObject>
#include <QThread>
#include <QTimer>
#include <QDebug>
#include <QString>
#include <QFile>
#include <QSocketNotifier>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
class Scanner : public QThread
{
Q_OBJECT
public:
static Scanner* getInstance(void);
int saveInCorrectFormat(int code);
protected:
void run() override;
signals:
void ChipScanned(QString rfid);
private slots:
void handleNotification(int socket);
void checkScannerData();
private:
Scanner(QObject *parent = 0);
~Scanner();
void initScanner(void);
static Scanner* sInstance;
QString defaultPath = "/dev/input/event2";
QString rfid;
QTimer* sCheckScanner;
QFile *sScannerFile;
QSocketNotifier *sNotifier;
int fd;
bool notificationEnabled;
struct input_event event;
int RFID[10];
int i = 0;
int buffer = 0;
};
#endif // SCANNER_H
scanner.cpp
#include "scanner.h"
Scanner* Scanner::sInstance = new Scanner();
Scanner* Scanner::getInstance(void){
return sInstance;
}
Scanner::Scanner(QObject *parent) : QThread(parent){
moveToThread(this);
start();
}
Scanner::~Scanner(){
}
void Scanner::run(){
initScanner();
QThread::exec();
}
/**
* #brief Scanner::initScanner
* initialize the timer to check up on the keyboard event file
*/
void Scanner::initScanner(void){
notificationEnabled = false;
sScannerFile = new QFile(defaultPath);
sCheckScanner = new QTimer(this);
sCheckScanner->setInterval(100);
sCheckScanner->setSingleShot(false);
connect(sCheckScanner, SIGNAL(timeout()), this, SLOT(checkScannerData()));
sCheckScanner->start();
}
/**
* #brief Scanner::checkScannerData
* check if the keyboard is connected or not
* if it is connected, activate event handling
*/
void Scanner::checkScannerData(){
if(sScannerFile->exists()){
if(notificationEnabled){
return;
}
fd = open(defaultPath.toUtf8().data(), O_RDONLY | O_NONBLOCK);
if(-1 != fd){
sNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(sNotifier, SIGNAL(activated(int)), this, SLOT(handleNotification(int)));
qDebug() << "Scanner connected";
notificationEnabled = true;
}
}else{
if(notificationEnabled){
sNotifier->setEnabled(false);
disconnect(sNotifier, SIGNAL(activated(int)), this, SLOT(handleNotification(int)));
delete sNotifier;
close(fd);
qDebug() << "Scanner disconnect";
notificationEnabled = false;
}
}
}
/**
* #brief Scanner::handleNotification
* check if the keyboard is still connected or if the event was the disconnect
* if still connected than read the data and save it
* #param socket
*/
void Scanner::handleNotification(int socket){
if(!sScannerFile->exists()){
if(notificationEnabled){
sNotifier->setEnabled(false);
disconnect(sNotifier, SIGNAL(activated(int)), this, SLOT(handleNotification(int)));
delete sNotifier;
close(fd);
qDebug() << "Scanner disconnect";
notificationEnabled = false;
}
return;
}
if(read(fd, &event, sizeof(event)) == sizeof(event)){
if(event.type != EV_SYN){
if(event.value == 1 && event.code != 28){
RFID[i] = saveInCorrectFormat(event.code);
rfid.append(QString("%1").arg(saveInCorrectFormat(event.code)));
i++;
}
}
}
if(rfid.size() == 10){
buffer++;
if(buffer == 10){
emit ChipScanned(rfid);
qDebug() << rfid;
i = 0;
buffer = 0;
rfid.clear();
}
}
}
/**
* #brief Scanner::saveInCorrectFormat
* correct the raw data in the it's right format
* #param code
* current data to convert
* #return
* converted data
*/
int Scanner::saveInCorrectFormat(int code){
switch(code){
case 11:
return 0;
case 28:
return -1;
default:
return code-1;
}
}
A few extra infos:
My device isn't really a keyboard but the input is handled as if it is a keyboard that's why I have to make a few tweaks with the raw data before it is in the expected format. Anyone else most likely won't need those tweaks, like int saveInCorrectFormat or the if condition after reading the data. I believe this code is rather universal which means changing the defaultPath and making a few tweaks while reading the raw data will probably make it possible to use it for other devices as well.

Using Thread in GUI application

I am making a multiple game. I need to take command from client. This means I have GUI and TcpServer. So I need to work them simultaneously. I used Thread but it doesnt work. Could you please help me to find the problem?
Summarizing: Firstly player press the "online" button. Then Oyun() Gui function runs and button connected with connectPressed() function. In this function there is a thread in order to run read the client commands when Gui is working.
Firstly I used QTimer in order to take command from Client in every 1 second. But My GUI freezed. And Then I used QThread but according to my research, QThread is not proper for GUI app. So I found Qtconcurrent, QFutureWatcher and QFuture. But my thread is still not working. I should have made a mistake somewhere.
#include <QApplication>
#include <anaclass.h>
#include <player2.h>
#include <tcpserver.h>
#include <QThread>
#include <QObject>
//#include <worker.h>
AnaClass *anaclass;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
anaclass = new AnaClass();
anaclass->show();
anaclass->Giris(); //button selection page
return a.exec();
}
#include "anaclass.h"
Puan *puanlama1;
Puan *puanlama2;
player2 *yilan2;
AnaClass::AnaClass() : QGraphicsView()
{
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setFixedSize(800,600);
scene = new QGraphicsScene;
scene->setSceneRect(0,0,800,600);
setScene(scene);
}
void AnaClass::Giris()
{
connectButton = new Button("Online");
double cxPos = this->width()/2 - connectButton->boundingRect().width()/2;
double cyPos= 425;
connectButton->setPos(cxPos, cyPos);
connect(connectButton, SIGNAL(clicked()), this, SLOT(connectPressed()));
scene->addItem(connectButton);
}
void AnaClass::Oyun()
{
scene->clear();
puanlama1 = new Puan();
puanlama1->setDefaultTextColor(Qt::blue);
puanlama1->setPos(5, 2);
scene->addItem(puanlama1);
yilan = new Yilan();
yilan->setRect(0,0,19,19);
scene->addItem(yilan);
yilan->setFlags(QGraphicsItem::ItemIsFocusable);
yilan->setFocus();
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(Qt::blue);
yilan->setBrush(brush);
if(stringButtonName == "Player2" || stringButtonName == "Online")
{
yilan->setPos(scene->width()/2 + 60, scene->height()/2);
}
else
{
yilan->setPos(scene->width()/2, scene->height()/2);
}
if(stringButtonName == "Player2" || stringButtonName == "Online")
{
yilan->playerNumber=1;
puanlama2 = new Puan();
puanlama2->setDefaultTextColor(Qt::green);
puanlama2->setPos(700, 2);
scene->addItem(puanlama2);
yilan2 = new player2();
yilan2->setRect(0,0,19,19);
scene->addItem(yilan2);
yilan2->setFlags(QGraphicsItem::ItemIsFocusable);
yilan2->setFocus();
QBrush brush2;
brush2.setStyle(Qt::SolidPattern);
brush2.setColor(Qt::green);
yilan2->setBrush(brush2);
yilan2->setPos(scene->width()/2 - 60,scene->height()/2);
}
emit emitTcp();
}
void AnaClass::connectPressed()
{
qDebug()<<"connect basildi";
server = new TCPServer();
server->Test();
stringButtonName = connectButton->buttonName;
qDebug()<<"Gelen Veri " + server->OkunanBilgi;
QFutureWatcher<void> watcher;
connect(&watcher, SIGNAL(finished()), server, SLOT(daimaOku()), Qt::QueuedConnection);
QFuture<void> deneme = QtConcurrent::run(this, &AnaClass::emitTcp);
watcher.setFuture(deneme);
Oyun();
}
}
#ifndef ANACLASS_H
#define ANACLASS_H
#include <QGraphicsScene>
#include <QGraphicsView>
#include <yilan.h>
#include <Meyve.h>
#include <QBrush>
#include <Puan.h>
#include <player2.h>
#include <QThread>
#include <label.h>
#include <QKeyEvent>
#include <button.h>
#include <QDebug>
#include <tcpserver.h>
#include <QTime>
#include <QTimer>
#include <QMutex>
//#include <worker.h>
#include <QFuture>
#include <QtConcurrent>
#include <QFutureWatcher>
class AnaClass : public QGraphicsView
{
Q_OBJECT
public:
AnaClass();
void Giris();
void Oyun();
void timerEvent(QTimerEvent *event);
void keyPressEvent(QKeyEvent *event2);
public:
Yilan *yilan;
//QThread *thread;
QGraphicsScene *scene;
Label *label1;
Button* player1Button;
Button* player2Button;
Button* connectButton;
TCPServer *server;
QTimer *timerOnline;
public:
int k=0;
int t=0;
QString stringButtonName;
signals:
void emitTcp();
public slots:
void connectPressed();
void player1Pressed();
void player2Pressed();
};
#endif // ANACLASS_H
#define TCPSERVER_H
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
#include <QObject>
#include <QTimer>
class TCPServer : public QObject
{
Q_OBJECT
public:
TCPServer(QObject* parent = nullptr);
void Test();
signals:
//void emitTcp();
public slots:
void newConnection();
void daimaOku(); // always read as english
public:
QTcpServer *server;
QTcpSocket *socket;
QTimer *timerTcp;
QString OkunanBilgi;
};
#endif // TCPSERVER_H
#include "tcpserver.h"
TCPServer::TCPServer(QObject * parent) : QObject()
{
}
void TCPServer::Test()
{
server = new QTcpServer();
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if(!server->listen(QHostAddress::Any, 1234))
{
qDebug()<<"server baslamadi";
}
else
{
qDebug()<<"server basladi";
}
//timerTcp = new QTimer();
//connect(timerTcp, SIGNAL(timeout()), this, SLOT(daimaOku()));
//emit emitTcp();
}
void TCPServer::newConnection()
{
qDebug()<<"newconnection";
socket = server->nextPendingConnection();
socket->write("Merhaba Client");
socket->flush();
socket->waitForBytesWritten(5000);
timerTcp->start(50);
}
void TCPServer::daimaOku() //alwaysread() as english
{
qDebug()<<"always read function is working";
// if(socket->state() == QAbstractSocket::ConnectedState)
// {
// qDebug()<<"Daima oku fonsiyonu soket bagli";
// socket->waitForReadyRead();
// OkunanBilgi = socket->readAll();
// qDebug()<<"Tcp daima oku :" + OkunanBilgi;
// }
}
Thank you for your comments. I solved the problem by deleting QFuture and adding connect() like below.
timerOnline = new QTimer();
connect(timerOnline, SIGNAL(timeout()), server, SLOT(daimaOku()));
timerOnline->start(500);
But I have another problem. When Client connects the server, my Gui app freezes. You can find the revised code below.
void TCPServer::daimaOku()
{
qDebug()<<"Function is running";
if(socket->state() == QAbstractSocket::UnconnectedState)
{
qDebug()<<"Socket is not connected";
}
else
{
qDebug()<<"Socket connected";
socket->waitForReadyRead();
OkunanBilgi = socket->readAll();
qDebug()<<"Tcp always read :" + OkunanBilgi;
}
}
When client is not connected, the output is:
Function is running
Socket is not connected
Socket is not connected ...
I can play the game but when client is connected, game freezes. I don't understand why.

Use QT to read from socket

I want to use IPC in order to exchange messages between two separate applications. The first one is a BASH script which is fired when a specific udev rule is activated (in Ubuntu Linux), and the other one is a simple Qt 5.7 console application, which acts as a server.
I already have the Qt server working and printing a message when it accepts a connection to the specified socket. What I'm trying to achieve now, is to make the server do something not when it accepts a connection, but when it receives a certain "message". Any ideas on how to do it?
Below is my code:
server.cpp
#include "server.h"
Server::Server() : QThread()
{
m_server = new QLocalServer(this);
m_server->listen("somesocket.sock");
connect(m_server, &QLocalServer::newConnection, this, &Server::testFunction);
}
Server::~Server()
{
m_server->removeServer("somesocket.sock");
}
void Server::run()
{
}
void Server::testFunction(){
qDebug() << "Sth happened!";
return;
}
server.h
#ifndef SERVER_H
#define SERVER_H
#include <QThread>
#include <QObject>
#include <QDebug>
#include <QLocalServer>
class Server : public QThread
{
public:
Server();
~Server();
void run();
void testFunction();
private:
QLocalServer *m_server;
signals:
void connectionEstablished(bool);
};
#endif // SERVER_H
You could connect to readyRead signal, and then check received message, like in this example:
connect( this, SIGNAL(readyRead()), SLOT(readClient()) );
void readClient()
{
QTextStream ts( this );
int line = 0;
while ( canReadLine() ) {
QString str = ts.readLine();
if(str == "someSpecialMessage")
{
//...
}
line++;
}
}
for more informations about this signal, see documentation: http://doc.qt.io/qt-5/qiodevice.html#readyRead
This is also an example of client and server applications in Qt, using QSocket and QServerSocket: https://doc.qt.io/archives/3.3/clientserver-example.html

Use of QAbstractSocket stateChanged()-Signal

What is the correct use/implementation of the QAbstractSocket stateChanged()-Signal?
main.cpp:
#include <QCoreApplication>
#include <sslserver.h>
#include <QLoggingCategory>
int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);
QLoggingCategory::setFilterRules("*.debug=true");
SslServer *myTestServer = new SslServer();
return a.exec();
}
SslServer.h:
#ifndef SSLSERVER_H
#define SSLSERVER_H
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
class SslServer : public QObject
{
Q_OBJECT
public:
explicit SslServer(QObject *parent = nullptr);
private slots:
void newTestConnection();
void sendTestdata();
void connectionWasClosed(QAbstractSocket::SocketState state = QAbstractSocket::UnconnectedState);
private:
QTcpServer *testServer;
QTcpSocket *testSocket;
QTimer *testTimer;
};
#endif // SSLSERVER_H
SslServer.cpp:
#include "sslserver.h"
#include <QDebug>
SslServer::SslServer(QObject *parent) : QObject(parent){
testServer = new QTcpServer(this);
testSocket = new QTcpSocket();
testTimer = new QTimer();
connect(testServer, SIGNAL(newConnection()), this, SLOT(newTestConnection())); //works
connect(testTimer, SIGNAL(timeout()), this, SLOT(sendTestdata())); //works
connect(testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(connectionWasClosed(QAbstractSocket::SocketState)));
//Qt5 Connection was also tested, without any change to old connection-typo
//connect(testSocket, &QAbstractSocket::stateChanged, this, &SslServer::verbindungWurdeBeendet);
testTimer->start(1000);
if(testServer->listen(QHostAddress::Any, 9999)){
qDebug() << "Server running on Port 9999";
}else{
qDebug() << "Error while building server";
}
}
void SslServer::newTestConnection(){
testSocket->close();
testSocket = testServer->nextPendingConnection();
testSocket->write("Welcome on: Testserver!");
testSocket->flush();
}
void SslServer::sendTestdata(){
if(testSocket->isOpen()){
qDebug() << testSocket->state();
qDebug() << "Sending testdata to client";
testSocket->write("testdata");
}
}
void SslServer::connectionWasClosed(QAbstractSocket::SocketState){
qDebug() << "!!! SocketState changed !!!";
}
I can see from the testSocket->state() statement that the state is changing from Unconnected to Connected to Unconnected, but the SLOT-Function is never called. What am I missing here?
The problem is caused because you are connecting to an object:
testSocket = new QTcpSocket();
But you expect to receive the signal from another object:
testSocket = testServer->nextPendingConnection();
The solution is to make the connection when you receive the new object:
void SslServer::newTestConnection(){
if(testSocket)
testSocket->close();
testSocket = testServer->nextPendingConnection();
connect(testSocket, &QAbstractSocket::stateChanged, this, &SslServer::connectionWasClosed);
testSocket->write("Welcome on: Testserver!");
testSocket->flush();
}
The complete example can be found in the following link
Your SLOT signature is not matching with SIGNAL.
Change the function declaration and definition to
void verbindungWurdeBeendet(QAbstractSocket::SocketState state);
And the connect statement to
connect(testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(verbindungWurdeBeendet(QAbstractSocket::SocketState)));
The SLOT function verbindungWurdeBeendet() (with out argument) is also acceptable, if you have default value in the function declaration.
ex:
In the below case you can have a SLOT in connect statement, without arguments.
void verbindungWurdeBeendet(QAbstractSocket::SocketState state = QAbstractSocket::UnconnectedState);

QTcpSocket gets NULL after QTcpServer::nextPendingConnection()

So I have a QTcpServer here (simplified version of Qt's Fortune Server Example). It was working fine earlier. Then I moved some things around and changed some code. Now my server crashes on start. As far as I can tell, after
tcpSocket = tcpServer->nextPendingConnection();
tcpSocket remains NULL. Thus all calls like tcpSocket->anyCall() will cause a seg fault. Application output shows:
QObject::connect: invalid null parameter
So my question is, why is tcpServer->nextPendingConnection() returning NULL
all of a sudden, when before I moved things around it worked just fine?
Here are the relevant parts of my code:
#include <QtWidgets>
#include <QtNetwork>
#include "server.h"
Server::Server(QWidget *parent)
: QDialog(parent), statusLabel(new QLabel), tcpServer(Q_NULLPTR), tcpSocket(Q_NULLPTR), networkSession(0), blockSize(0), userAuthenticated(false)
{
QNetworkConfigurationManager manager;
QNetworkConfiguration config = manager.defaultConfiguration();
networkSession = new QNetworkSession(config, this);
sessionOpened();
...
// GUI stuff here //
...
this->read_newClient();
}
void Server::sessionOpened()
{
tcpServer = new QTcpServer(this);
// some if else checks here //
tcpSocket = tcpServer->nextPendingConnection(); // problem here //
connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, &QObject::deleteLater); // line that crashes //
}
void Server::read_newClient()
{
QString data;
if (!clientSocket->waitForReadyRead())
{
qDebug() << "Cannot read";
return;
}
data = readData();
}
To use nextPendingConnection you need incomming connection. Therefore you have two ways:
Connect to signal newConnection():
...
connect(tcpServer, &QTcpServer::newConnection, this, &Server::OnNewConnection);
...
void Server::OnNewConnection() {
if (tcpServer->hasPendingConnections()) {
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater);
}
}
Or use blocking call waitForNewConnection():
if (tcpServer->waitForNewConnection()) {
if (tcpServer->hasPendingConnections()) {
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater);
}
}
Do not forget call tcpServer->listen();