I'm trying to perform a network connectivity check whenever user opens the app or whenever app comes in foreground. Below is the sample code
void ApplicationUI::onFullscreen()
{
qDebug()<<"Application has entered foreground";
QNetworkConfigurationManager mgr;
QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations(QNetworkConfiguration::Active);
if (activeConfigs.count() > 0)
{
qDebug()<<"Has Internet connection";
}
else
{
qDebug()<<"No Internet connection";
}
}
This always prints Has Internet connection even when the network connection is off. Any ideas?
You can use QNetworkConfigurationManager.isOnline().
QNetworkConfigurationManager mgr;
mgr.isOnline();
If you want to get notified about changes of the online state then you also can connect to the QNetworkConfigurationManager::onlineStateChanged(bool isOnline) signal.
connect(mgr, SIGNAL(onlineStateChanged(bool)), this, SLOT(onOnlineStateChanged(bool)));
Related
I am trying to achieve a signal when the internet is disconnected for an already connected SSL socket. Here is the way I have derived the QSslSocket:
struct CloudSSL::Socket : public QSslSocket
{
Q_OBJECT public:
void ConnectSlots ()
{
connect(this, SIGNAL(readyRead()), this, SLOT(ReceiveData()));
connect(this, SIGNAL(disconnected()), this, SLOT(Disconnected()));
// *** None of the above or below is invoking when internet disconnects ***
connect(this, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(Error(QAbstractSocket::SocketError)));
}
virtual ~Socket ()
{
QObject::disconnect();
QSslSocket::abort();
}
public slots:
void ReceiveData ()
{
LOG("Socket received data...");
}
void Disconnected ()
{
LOG("Socket got disconnected...");
}
void Error (QAbstractSocket::SocketError error)
{
LOG("Socket error ", error);
}
}
Here is how it's initialized:
m_pSSLSocket = new Socket;
m_pSSLSocket->setProtocol(QSsl::TlsV1_2);
m_pSSLSocket->setLocalCertificateChain(QSslCertificate::fromPath(":/Certificate.pem", QSsl::Pem));
m_pSSLSocket->setPrivateKey(QSslKey(privateKeyFile.readAll(), QSsl::Rsa));
m_pSSLSocket->setSocketOption(QAbstractSocket::LowDelayOption, true); // <---
m_pSSLSocket->setSocketOption(QAbstractSocket::KeepAliveOption, true); // <---
m_pSSLSocket->connectToHostEncrypted(SAARATHY_URL, SAARATHY_PORT);
m_pSSLSocket->ignoreSslErrors();
Things work fine in general. However, if I disable wifi in my Ubuntu PC, then I don't get any network error as expected from the QAbstractSocket::SocketError:
QAbstractSocket::NetworkError -- 7 -- An error occurred with the network
(e.g., the network cable was accidentally plugged out).
Referred following posts before this Qn:
QTcpSocket state always connected, even unplugging ethernet wire
Qt TCP/IP socket connection check
Question: What is the Qt exclusive way of receiving a signal when the internet is disconnected?
Unless the protocols you use have some sort of keep-alive, if you don't send anything nothing will be sent and no attempt of error checking will be done.
If you want to see if there's problem with a connection you actually have to send something. If a cable is unplugged or there is any other problem between you and the remote host, then (after a suitable timeout and retries) you will get an error.
To see if the remote host has closed the connection in a nice way, you have to attempt to read something, in which case the receive call will return that it has read zero bytes.
I want to search bluetooth devices available and list them but the code I am following from documenation doesn't work.
BluetoothDevices::BluetoothDevices(QObject *parent) : QObject(parent)
{
}
// search Bluetooth devices
void BluetoothDevices::startDeviceDiscovery()
{
qDebug() << "Bluetooth discovery started";
// Create a discovery agent and connect to its signals
//QBluetoothDeviceDiscoveryAgent *discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this, SLOT(deviceDiscovered(QBluetoothDeviceInfo)));
// Start a discovery
discoveryAgent->start();
}
void BluetoothDevices::deviceDiscovered(const QBluetoothDeviceInfo &device)
{
qDebug() << "Found new device:" << device.name() << '(' << device.address().toString() << ')';
}
In main window I start the search:
void MainWindow::on_pushButtonSearchBluetooth_clicked()
{
bluetoothDevices.startDeviceDiscovery();
}
I expect the deviceDiscovered() slot to get called with the device names as it gets found but this slot never gets called. I never hear anything back after initiating discovery. When I do search bluetooth devices manually from control panel, it does find couple of laptops. What else do I need to do to find them through my app?
I am using windows 7 and Qt 5.5.
I have the same problem. You can connect signal
connect(m_discoveryAgent, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error)), this, SLOT(error(QBluetoothServiceDiscoveryAgent::Error))); and you can see that slot emitted with error InvalidBluetoothAdapterError.
I try it on WIN7 and WIN10 and it not worked. In Ubuntu the same code work properly.
It seems that bluetooth not supported in windows platforms.
Currently, the API is supported on the following platforms: Android, iOS, Linux (BlueZ 4.x/5.x) and OS X.
from http://doc.qt.io/qt-5/qtbluetooth-index.html
I am using QTcpSocket to send data between a client and a server.
The server works perfectly fine on Linux, yet on Windows it will only receive one message and not more after that. readyRead() is just never emitted again.
Does anyone know what could be the problem?
Some of the code which I deemed to be important for this question:
server sending:
void Server::sendData(Client *client, QString data)
{
if (client->socketDescriptor == socketDescriptor) {
data = data + CRLF;
// Have also tried to use socket->flush(), same problem.
socket->write(data.toUtf8());
socket->waitForBytesWritten();
}
}
server receiving:
// this slot is connected to the readyRead() signal
void Server::readData()
{
// on Windows this is called exactly once for each client
// every additional messages just don't seem to arrive at the server
QString msg = QString(socket->readAll());
emit receivedData(this, &msg);
}
I just don't get why it works on Linux, yet not on windows...
REQUIREMENT
A Client Server Application
Communication will be done by thrift
Server will be running in background or invoked through terminal with no GUI
Client will be Qt based
Current Scenario and problem
Currently, the server uses TNonBlockingServer with certain number of threads(using threadmanager)
Clients connect to the server and does the job.
But, there is a certain requirement where if my server is not running and client tries to connect to it then a message box should be displayed in client's screen.
Currently program just gives a segmentation fault, so i tried using try catch, which didn't work. Upon searching i noticed that Qt doesn't support Exceptions.
Upon some more searching i came across This, but this seems to be using QT(and I still don't know if my problem can be resolved by this)
Server Code :
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
shared_ptr<workerHandlerHandler> handler(new workerHandlerHandler());
shared_ptr<TProcessor> processor(new workerHandlerProcessor(handler));
shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(15);
shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());
threadManager->threadFactory(threadFactory);
threadManager->start();
TNonblockingServer server(processor, protocolFactory, port,threadManager);
server.serve();
Client connects using
boost::shared_ptr<TSocket> socket(new TSocket(serverip.toUtf8().data(), 59999));
boost::shared_ptr<TTransport> transport(new TFramedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
workerHandlerClient client(protocol);
transport->open();
int pingValue = client.ping();
transport->close();
Why not use something like:
QTcpSocket *socket = new QTcpSocket();
socket->connectToHost(serverip, serverport);
if(!socket->waitForConnected(time-in-msecs))
QMessageBox::critical(some-ui-window-as-parent, "Error Title", "Error connecting Text");
If the client is Qt based, you can use QTcpSocket to connect the server :
QTcpSocket clientSocket;
By connecting the error signal of the client socket to a slot, you can display appropriate message box when an error occurs. If the server is not running and the client tries to connect, the slot is called and a message box containing the error is shown :
connect( &clientSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(tcpError(QAbstractSocket::SocketError)) );
clientSocket.connectToHost(ipAddress, portNo );
The slot is as :
void MyClass::tcpError(QAbstractSocket::SocketError error)
{
QMessageBox::warning( this, tr("Error"),tr("TCP error: %1").arg( clientSocket.errorString() ) );
clientSocket.disconnectFromHost();
}
I don't know what you really mean.Qt just support try and catch.
Now, I'm developing a program which is similar with your program.
I also use No-QT server and QT client, but in my code I use the struct like below:
try
{
}
catch(TException e)
{
QMessageBox::information(this, "Warn", "Thrift server has shut down");
}
And it works well
I'm using Qt and trying to create a Client - Server connection. Whenever I click a button in my client application, a socket connects to the server and sends some data. The problem is I don't know how to receive the data. These are the slots for my buttons.
void MainWindow::func_button_one(){
socket->connectToHost("127.0.0.1", 1324);
if(socket->waitForConnected(1000)) {
socket->write("button one has been pressed");
socket->waitForBytesWritten(1000);
}
else {
qDebug() << "Something terrible seems to have happened.";
}
}
Now, in my server application, I tried something like this.
void MainWindow::newConnection(){
QTcpSocket *socket = server->nextPendingConnection();
socket->waitForReadyRead(1000);
qDebug() << "connection received";
qDebug() << socket->readAll();
socket->close();
}
The connection is all right, because the "connection received" message shows up. So, how am I supposed to receive the data from the client? QTcpServer doesn't have any read() function.
The connection is all right, because waitForReadyRead returned 'true', or the connection is not all right, because waitForReadyRead returned false after 1000ms. How would you know the difference?
Better work asynchronously with signals. Connect your socket to 'readyRead()'. Or at least test the return value of waitForReadyRead.