Console Chat Using QTcpSocket and QTcpServer - c++

I want to write a console chat program in qt framework.I have a problem with sending messages.
Client sends messages to server but server doesn't take the messages until client program is closed.When client is closed, server displays all messages.I don't want that.I want server to get my messages when i send to it.
I wrote the codes below.You will see what i want to do if you look at main function of client.
/*
Created BY :
Creation DATE : 26/10/2012
Client interface
*/
#ifndef CLIENT_H
#define CLIENT_H
#include <QtNetwork>
#include <QObject>
#include <QtNetwork/QTcpSocket>
namespace NetworkArdic
{
class Client : public QObject
{
Q_OBJECT
public:
Client(QObject * obj = 0,QString add="localhost", quint16 port = 4000);
void SendData(QString data);
virtual ~Client();
private slots:
void ReadData();
void connected();
private:
QTcpSocket *socket;
};
}
#endif
/*
Created BY :
Creation DATE : 26/10/2012
Client source file
*/
#include "Client.h"
#include <QHostAddress>
#include <iostream>
using namespace std;
namespace NetworkArdic{
Client::Client(QObject * obj, QString add, quint16 port) : QObject(obj)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(ReadData()));
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
socket->connectToHost(QHostAddress(add), port);
}
Client::~Client(){
socket->close();
delete socket;
}
void Client::SendData(QString data)
{
if(!data.isEmpty())
{
socket->write(QString(data + "\n").toUtf8());
}
}
void Client::ReadData()
{
while(socket->canReadLine())
{
QString line = QString::fromUtf8(socket->readLine()).trimmed();
qDebug() << line;
}
}
void Client::connected()
{
socket->write(QString("Client : Server connection has been made (: \n").toUtf8());
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Client cli(0,"127.0.0.1",4000);
string line;
while(line!="exit"){
cout << "Message : ";
cin >> line;
cli.SendData(QString(line.c_str()));
}
return a.exec();
}
/*
Created BY :
Creation DATE : 26/10/2012
Server interface
*/
#ifndef SERVER_H
#define SERVER_H
#include <QtNetwork>
#include <QObject>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
namespace NetworkArdic
{
class Server: public QTcpServer
{
Q_OBJECT
public:
Server(QObject * parent = 0 , quint16 port = 4000);
virtual ~Server();
private slots:
void acceptConnection();
void startRead();
void disconnected();
private:
QTcpSocket * client;
};
}
#endif // SERVER_H
/*
Created BY :
Creation DATE : 26/10/2012
Server source file
*/
#include "Server.h"
#include <iostream>
using namespace std;
namespace NetworkArdic{
Server::Server(QObject* parent , quint16 port): QTcpServer(parent)
{
connect(this, SIGNAL(newConnection()),this, SLOT(acceptConnection()));
listen(QHostAddress::Any, port );
}
Server::~Server()
{
delete client;
close();
}
void Server::acceptConnection()
{
client = nextPendingConnection();
connect(client, SIGNAL(readyRead()), this, SLOT(startRead()));
connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
qDebug() << "New client from:" << client->peerAddress().toString();
}
void Server::startRead()
{
while(client->canReadLine())
{
QString line = QString::fromUtf8(client->readLine()).trimmed();
qDebug() << "Client :" << line;
client->write(QString("Server : I've taken your message (:\n").toUtf8());
}
}
void Server::disconnected()
{
qDebug() << "Client disconnected:" << client->peerAddress().toString();
client->write(QString("Server : I wish you didn't leave ):\n").toUtf8());
}
}

Try using socket->flush() after you write the data.
http://doc.qt.digia.com/qt/qabstractsocket.html#flush

You used the code below to read socket data.
void Server::startRead()
{
while(client->canReadLine())
{
QString line = QString::fromUtf8(client->readLine()).trimmed();
qDebug() << "Client :" << line;
client->write(QString("Server : I've taken your message (:\n").toUtf8());
}
}
I suggest to adopt from the following code which I have tested works
while (tcp_server->hasPendingConnections()) {
client = tcp_server->nextPendingConnection();
client->waitForReadyRead(100);
QByteArray byteArray = client->readAll();
QString s_data = byteArray.data();
// Process s_data
client->close();
client->abort();
}

Related

I have created a TCPSocket in QT, but how do i implement received data from QTCPSocket?

As the title says, i have created a client which receives data from my server. So far i can print it in my console, but i would like to work with it. (The data that the client recevies is from my Smartphones accelerometer sensor)
My Socket.h class:
#ifndef SOCKETTEST_H
#define SOCKETTEST_H
#include <QObject>
#include <QDebug>
#include <QTcpSocket>
#include <QAbstractSocket>
class SocketTest : public QObject
{
Q_OBJECT
public:
explicit SocketTest(QObject *parent = nullptr);
void Test();
signals:
public slots:
void connected();
void disconnected();
void bytesWritten( qint64 bytes);
void readyRead();
private:
QTcpSocket *socket;
};
#endif // SOCKETTEST_H
and socket.cpp :
#include "sockettest.h"
SocketTest::SocketTest(QObject *parent)
: QObject{parent}
{
}
void SocketTest::Test()
{
socket = new QTcpSocket(this);
connect (socket, SIGNAL(connected()),this, SLOT(connected()));
connect (socket, SIGNAL(disconnected()),this, SLOT(disconnected()));
connect (socket, SIGNAL(readyRead()),this, SLOT(readyRead()));
connect (socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));
qDebug() <<"Connecting...";
socket->connectToHost("MY IP", PORT);
if(!socket->waitForConnected(2000))
{
qDebug() <<"Error" << socket->errorString();
}
}
void SocketTest::connected()
{
qDebug() <<"Connected!";
socket->write("\r\n\r\n\r\n\r\n");
}
void SocketTest::disconnected()
{
qDebug() <<"Disconnected!";
}
void SocketTest::bytesWritten(qint64 bytes)
{
qDebug() <<"We wrote: " <<bytes;
}
void SocketTest::readyRead()
{
qDebug() << socket->readAll();
}
typically what i want to create, in another class, is an if statment which moves an Object based on the sent data :
if( received_data == 5 ){
this->setX(this->x()+1);
}

I can't see the ip address using QHostAddress::LocalHost through UDP with QUdpSocket

i'm planning do a little app desktop with Qt Creator. I'm using QUdpSocket class to make a simple connection through UDP, in fact i used a test code i found on internet, but my problem is when i run the code and the console just show me the port and the message, not the ip address where come from the message. Could someone tell me what i'm doing bad?
The source reference is this
This is the header file:
#ifndef PRUEBAUDP_H
#define PRUEBAUDP_H
#include <QObject>
#include <QUdpSocket>
#include <QDebug>
/*#include <QNetworkDatagram>
#include <QHostAddress>*/
class pruebaUDP : public QObject
{
Q_OBJECT
public:
explicit pruebaUDP(QObject *parent = nullptr);
void mensajeSocket();
signals:
public slots:
void readyRead();
private:
QUdpSocket *udpSocket;
};
#endif // PRUEBAUDP_H
This is the source file:
#include "pruebaudp.h"
pruebaUDP::pruebaUDP(QObject *parent) : QObject(parent)
{
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 1234);
connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(readyRead()));
}
void pruebaUDP::mensajeSocket()
{
QByteArray dato;
dato.append("hola");
udpSocket->writeDatagram(dato, QHostAddress::LocalHost, 1234);
}
void pruebaUDP::readyRead()
{
QByteArray buffer;
buffer.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);
qDebug() << "Desde: " << sender.toString();
qDebug() << "mensaje del puerto: " << senderPort;
qDebug() << "mensaje: " << buffer;
}
and this is the main file:
#include <QCoreApplication>
#include "pruebaudp.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
pruebaUDP prueba;
prueba.mensajeSocket();
return a.exec();
}
This is a input screenshot:
You use same socket for sending and receiving.
Try to send data via other socket, i.e.
void pruebaUDP::mensajeSocket()
{
QByteArray dato;
dato.append("hola");
static QUdpSocket * socket = new QUdpSocket(this);
socket->writeDatagram(dato, QHostAddress::LocalHost, 1234);
}

how to send an audio stream via tcp in a thread in Qt?

I'm trying to send an audio stream from a microphone via TCP in a thread other than the main thread. Therefore I've set up a server an I'm listening for incoming connections. Once a client connects, I want to send it the audio stream. I've read the Qt Documentation about QTcpServer, Multithreading, and QtMultimedia. I've also looked at this website for example code about multithreading and TCP servers in Qt. The problem is this message that I get during runtime:
QObject: Cannot create children for a parent that is in a different thread. (Parent is QNativeSocketEngine(0xae802a78), parent's thread is MyThread1(0x1856d28), current thread is QThread(0x1838aa0)
this is my code:
in file myserver.h
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QtNetwork>
#include <QTcpServer>
#include <mythread.h>
#include <QtMultimediaKit/QAudioFormat>
#include <QtMultimediaKit/QAudioInput>
#include <QtMultimediaKit/QAudioDeviceInfo>
class MyServer : public QTcpServer
{
Q_OBJECT
public:
explicit MyServer(QObject *parent = 0);
void startServer();
signals:
public slots:
protected:
void incomingConnection(int socketDescriptor);
private:
QAudioInput *audioInput;
};
#endif // MYSERVER_H
in file myserver.cpp
#include "myserver.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::startServer()
{
int port = 12345;
QString ipAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
for (int i = 0; i < ipAddressesList.size(); ++i)
{
if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address())
{
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
if(!this->listen( QHostAddress(ipAddress),port ) )
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "The server is running on\n\nIP: "<< ipAddress;
qDebug() << "\nport: " << this->serverPort() << "\n\n";
}
}
void MyServer::incomingConnection(int socketDescriptor)
{
qDebug() << socketDescriptor << " Connecting...";
QAudioFormat format;
format.setSampleRate(44100);
format.setChannelCount(1);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
if (!info.isFormatSupported(format))
{
qWarning()<<"default format not supported try to use nearest";
format = info.nearestFormat(format);
}
audioInput = new QAudioInput(format, this);
MyThread1 *thread = new MyThread1(socketDescriptor,audioInput, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
in file mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QDebug>
#include <QtMultimediaKit/QAudioInput>
class MyThread1 : public QThread
{
Q_OBJECT
public:
explicit MyThread1( int ID, QAudioInput *spk, QObject *parent = 0);
void run();
signals:
void error(QTcpSocket::SocketError socketerror);
public slots:
void sendData();
void disconnected();
private:
QTcpSocket *socket;
int socketDescriptor;
QAudioInput *speaker;
};
#endif // MYTHREAD_H
in file mythread.cpp
#include "mythread.h"
MyThread1::MyThread1( int ID, QAudioInput *spk, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
this->speaker = spk;
}
void MyThread1::run()
{
qDebug() << " Thread started";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect( speaker->start(), SIGNAL( readyRead() ), this, SLOT( sendData() ) , Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
qDebug() << socketDescriptor << " Microphone connected";
exec();
}
void MyThread1::sendData()
{
QByteArray Data = speaker->start()->readAll();
QDataStream l_vStream(&Data, QIODevice::WriteOnly);
l_vStream.setByteOrder(QDataStream::LittleEndian);
socket->write(Data, Data.length());
socket->waitForBytesWritten();
}
void MyThread1::disconnected( )
{
qDebug() << socketDescriptor << "Mic Disconnected";
speaker->stop();
delete speaker;
socket->deleteLater();
exit(0);
}
in file main.cpp
#include <QCoreApplication>
#include <myserver.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyServer server;
server.startServer();
return a.exec();
}
Any help would really be appreciated. Thanks.

Connection to server fails in qt

I created a small server/client application, and for testing I put the server/client function into a separate application.
The main client functions are
Client::Client(QString purpose) : networkSession(0)
{
Client::purpose = purpose;
tcpSocket = new QTcpSocket;
Client::blockSize = 0;
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(displayError(QAbstractSocket::SocketError)));
QNetworkConfigurationManager manager;
if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
{
// Get saved network configuration
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
settings.beginGroup(QLatin1String("QtNetwork"));
const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
settings.endGroup();
// If the saved network configuration is not currently discovered use the system default
QNetworkConfiguration config = manager.configurationFromIdentifier(id);
if ((config.state() & QNetworkConfiguration::Discovered) !=
QNetworkConfiguration::Discovered) {
config = manager.defaultConfiguration();
}
networkSession = new QNetworkSession(config, this);
connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
}
qDebug() << "Client set up, waiting";
}
void Client::connectToServer(QString ipAddr, quint32 port)
{
qDebug() << "Connecting to Host on port " << port << ' ' << (quint16)port;
tcpSocket->connectToHost(ipAddr, port);
emit this->connectionResult((tcpSocket->state() == QAbstractSocket::UnconnectedState)?false:true);
if (tcpSocket->waitForConnected(1000))
qDebug("Connected!");
qDebug() << "Am I connected" << tcpSocket->state();
std::cout << "Am I not connected" << tcpSocket->state();
}
and the server-functions:
Server::Server(QString ipAddr, quint32 port, QString purpose)
: tcpServer(0), networkSession(0)
{
Server::clientConnection = NULL;
Server::purpose = purpose;
Server::port = port;
QNetworkConfigurationManager manager;
if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
// Get saved network configuration
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
settings.beginGroup(QLatin1String("QtNetwork"));
const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
settings.endGroup();
// If the saved network configuration is not currently discovered use the system default
QNetworkConfiguration config = manager.configurationFromIdentifier(id);
if ((config.state() & QNetworkConfiguration::Discovered) !=
QNetworkConfiguration::Discovered) {
config = manager.defaultConfiguration();
}
networkSession = new QNetworkSession(config, this);
connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
//statusLabel->setText(tr("Opening network session."));
networkSession->open();
} else {
sessionOpened();
}
//connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(openNewConnection()));
//connect(tcpServer, &QTcpServer::newConnection, this, &Server::openNewConnection);
}
void Server::sessionOpened()
{
// Save the used configuration
if (networkSession) {
QNetworkConfiguration config = networkSession->configuration();
QString id;
if (config.type() == QNetworkConfiguration::UserChoice)
id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
else
id = config.identifier();
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
settings.beginGroup(QLatin1String("QtNetwork"));
settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
settings.endGroup();
}
tcpServer = new QTcpServer(this);
if (!tcpServer->listen(QHostAddress::Any, Server::port)) {
return;
}
qDebug() << "Server listening on: " << tcpServer->serverPort();
//! [0]
QString ipAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
//! [1]
}
void Server::openNewConnection(void)
{
qDebug() << "New conn incoming!";
Server::clientConnection = tcpServer->nextPendingConnection();
QVariant ipAddr_QVar(clientConnection->peerAddress().toString());
qDebug() << "Got new connection!";
emit gotNewConnection(ipAddr_QVar);
}
The main problem here is that even if I get a "Connected" from
if (tcpSocket->waitForConnected(1000))
qDebug("Connected!");
qDebug() << "Am I connected" << tcpSocket->state();
in the client function, but the server function openNewConnection() never gets called. Why? How can I find the bug?
If a minimal working example is necessary, I can provide the whole code, but here I just wanted to provide the most important functions.
Edit:
client.h:
#ifndef CLIENT_H
#define CLIENT_H
//#include <QDialog>
#include <iostream>
#include <QTcpSocket>
class QComboBox;
class QDialogButtonBox;
class QLabel;
class QLineEdit;
class QPushButton;
class QTcpSocket;
class QNetworkSession;
class Client : public QObject
{
Q_OBJECT
private:
QTcpSocket *tcpSocket;
QString currentFortune;
quint16 blockSize;
QPair<QString, QPair<QString, QVariant> > data;
QNetworkSession *networkSession;
QString purpose;
signals:
void gotData(QPair<QString, QPair<QString, QVariant> >);
void noConnection(void);
void connectionResult(bool);
void isDisconnect(bool);
public slots:
void displayError(QAbstractSocket::SocketError socketError);
void sessionOpened();
void getInfo();
void readData();
void connectToServer(QString ipAddr, quint32 port);
void disconnectFromServer();
private:
public:
Client(QString purpose);
};
#endif // CLIENT_H
server.h:
#ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
#include <iostream>
//#include <QtTest/QTest>
#include <QSignalSpy>
#include <QTcpSocket>
#include <QDebug>
//#include <QMessageBox>
#include <QNetworkInterface>
#include <typeinfo>
#include <QStringList>
//#include <QSignalSpy>
QT_BEGIN_NAMESPACE
class QTcpServer;
class QNetworkSession;
QT_END_NAMESPACE
class Server : public QObject
{
Q_OBJECT
public slots:
void sessionOpened();
void sendFortune(void);
void sendData(QPair<QString, QPair<QString, QVariant> > data);
void sendFile(QVariant fileName);
void disconnectServer(void);
void openNewConnection(void);
signals:
void gotNewConnection(QVariant);
private:
QString purpose;
QTcpServer *tcpServer;
QString ipAddr;
quint32 port;
QTcpSocket *clientConnection;
quint32 BlockSize;
bool firstTime;
QSignalSpy * m_pSignalSpy;
QStringList fortunes;
QNetworkSession *networkSession;
//QNetworkConfiguration config;
public:
Server(QString ipAddr, quint32 port, QString purpose = "");
};
#endif // SERVER_H
The problem lies with your QNetworkSession, you have declared it in scope. Meaning once you leave that function the QNetworkSession gets destroyed. A destroyed object cannot emit a signal. Maybe make it a member variable or construct it in your header.

Simple QSsl client/server : cannot start handshake on non-plain connection

I try to create a simple ssl connection between a client and a server in QtNetwork.
But I have a problem. First I run the server. Then I run the client. When I first run the client nothing happens, but when I run it second time I get QSslSocket::startServerEncryption: cannot start handshake on non-plain connection. I don't know how to fix it.
Here is the server:
//server.h
#ifndef SERVER_H
#define SERVER_H
#include <QtNetwork>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QSslSocket>
class Server: public QTcpServer
{
Q_OBJECT
public:
Server(QObject * parent = 0);
void incomingConnection(int handle);
~Server();
public slots:
void startRead();
private:
QSslSocket* socket;
};
#endif // SERVER_H
Server Source File :
//server.cpp
#include "server.h"
#include <iostream>
#include <QByteArray>
#include <QSslCertificate>
#include <QSslKey>
using namespace std;
Server::Server(QObject* parent) :
QTcpServer(parent)
{
socket = new QSslSocket;
connect(socket, SIGNAL(encrypted()),
this, SLOT(startRead()));
listen(QHostAddress::Any, 8889);
}
void Server::startRead()
{
char buffer[1024] = { 0 };
socket->read(buffer, socket->bytesAvailable());
cout << buffer << endl;
socket->close();
}
void Server::incomingConnection(int socketDescriptor)
{
if (socket->setSocketDescriptor(socketDescriptor))
{
connect(socket, SIGNAL(encrypted()),
this, SLOT(startRead()));
QByteArray key;
QByteArray cert;
QFile file_key("/path_to_key/rsakey");
if(file_key.open(QIODevice::ReadOnly))
{
key = file_key.readAll();
file_key.close();
}
else
{
qDebug() << file_key.errorString();
}
QFile file_cert("/path_to_certificate/mycert.pem");
if(file_cert.open(QIODevice::ReadOnly))
{
cert = file_cert.readAll();
file_cert.close();
}
else
{
qDebug() << file_cert.errorString();
}
QSslKey ssl_key(key, QSsl::Rsa);
QSslCertificate ssl_cert(cert);
socket->setPrivateKey(ssl_key);
socket->setLocalCertificate(ssl_cert);
QSslConfiguration cfg = socket->sslConfiguration();
cfg.caCertificates();
socket->startServerEncryption();
}
}
Server::~Server()
{
delete socket;
}
Server Main File :
//server main
#include "server.h"
#include <QCoreApplication>
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
Server server;
return app.exec();
}
Here is the Client :
//client.h
#ifndef CLIENT_H
#define CLIENT_H
#include <QtNetwork>
#include <QObject>
#include <QString>
#include <QSslSocket>
class Client: public QObject
{
Q_OBJECT
public:
Client(QObject* parent = 0);
~Client();
void start(QString address, quint16 port);
public slots:
void startTransfer();
private:
QSslSocket client;
};
#endif // CLIENT_H
Client Source File :
// client.cpp
#include "client.h"
#include <QDebug>
Client::Client(QObject* parent) :
QObject(parent)
{
connect(&client, SIGNAL(encrypted()),
this, SLOT(startTransfer()));
}
Client::~Client()
{
client.close();
}
void Client::start(QString address, quint16 port)
{
client.connectToHostEncrypted(address, port);
}
void Client::startTransfer()
{
qDebug() << "startTransfer()";
client.write("Hello, world", 13);
}
Client Main File :
//client main
#include "client.h"
#include <QCoreApplication>
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
Client client;
client.start("127.0.0.1", 8889);
return app.exec();
}
Anyone can tell me what's missing?
The problem here is that QSslSocket can't be reused (I opened a bug about this QTBUG-59348), so once you call setSocketDescriptor for the second time (once a new connection arives) the internal mode is in Encrypted state.
Your code also has the issue that even if QSslSocket could be reused, you create a single socket at the constructor, so you can only accept a single connection at time. You must instead create a new QSslSocket inside incommingConnection, and NO YOU DON'T NEED to call nextPendingConnection() if you have an implementation of QTcpServer, if you do you will get two objects pointing to the same FD, one QTcpSocket and one QSsqSocket created by you.
You should try to get the socket descriptor from the nextPendingConnection and set the socket descriptor of the QSslsocket
First: You have to connect the signal of the QTcpServer::newConnection with a self made slot (for example newConnectionRecognized)
Second: Set the socketDescriptor of the QSslSocket with the socket descriptor of the QTcpServer::nextPendingConnection()->socketDescriptor
constructor:
{
server = new QTcpServer;
...
server->listen(QHostAddress::Any,1234)
...
connect(server,SIGNAL(newConnection()),this,SLOT(newConnectionRecognized()));
...
}
void SslServer::newConnectionRecognized()
{
incomingConnection(server->nextPendingConnection()->socketDescriptor());
...
}
void SslServer::incomingConnection(int socket_descriptor)
{
socket = new QSslSocket(this);
...
if (!socket->setSocketDescriptor(socket_descriptor))
{
qWarning("! Couldn't set socket descriptor");
delete socket;
return;
}
...
}
I hope it helped...