Runtime Error: could not start server - c++

I wrote a client server program in Qt that client send some message to server but during compile the "startserver" function can't run and i get the following error:could not start server. Could you please say where is problem?
"main.cpp"
#include <QApplication>
#include "mythread.h"
#include "myserver.h"
#include "QtSql/QtSql"
#include "QMessageBox"
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
myserver server;
server.startserver();
MainWindow w;
w.show();
return a.exec();
}
"myserver.h"
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QMainWindow>
#include "QTcpServer"
#include "mythread.h"
#include "QTcpSocket"
namespace Ui
{
class myserver;
}
class myserver : public QObject
{
Q_OBJECT
public:
server(QObject * parent = 0);
explicit myserver(QObject *parent = 0);
void startserver();
public slots:
void acceptConnection();
protected:
void incomingConnections(qintptr socketDescriptor);
QTcpSocket* c_client;
QTcpServer s_server;
private:
qintptr socketDescriptor;
};
#endif
"myserver.cpp"
#include "myserver.h"
#include "mythread.h"
myserver::myserver(QObject *parent) :
QObject(parent)
{
}
void myserver::startserver()
{
int port = 1234;
if(s_server.listen(QHostAddress::Any, port))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening to port " ;
}
}
void myserver::incomingConnections(qintptr socketDescriptor)
{
mythread *thread = new mythread(socketDescriptor,this);
qDebug() << socketDescriptor << " Connecting...";
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
void myserver::acceptConnection()
{
c_client = s_server.nextPendingConnection();
connect(c_client,SIGNAL(readyRead()),this, SLOT(startRead()));
qDebug() << " Connecting...";
}

if(s_server.listen(QHostAddress::Any, port))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening to port " ;
}
reads as "if the server CAN listen to any address on given port, print could not start server"
just change it to if (!s_server.listen(...)) and the missleading message should be gone

Related

can't open the serial port from qt

I am working on a project where I have to write to an read from a serial port. I have written the following code, but I am getting the message "can't open the port" in my else statement.
When I use hercules, I can open the "COM1" port. But I don't know why can't I open this port via my QT program.
code:
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtSerialPort/QSerialPort>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
QSerialPort *serial;
private slots:
void on_pushButton_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QtSerialPort/QSerialPort>
#include <QSerialPortInfo>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
serial = new QSerialPort(this);
serial->setPortName("COM1");
for(const auto &serialPortInfo : QSerialPortInfo::availablePorts())
{
qDebug() << "find serial port: " << serialPortInfo.portName() ;
}
serial->open(QIODevice::ReadWrite);
if(serial->open(QIODevice::ReadWrite))
{
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
while(1)
{
serial->write("ok");
qDebug() << " Reading " << serial->read(1);
serial->flush();
}
}
else
{
qDebug() << "can't open the port";
}
}
Widget::~Widget()
{
delete ui;
serial->close();
}
void Widget::on_pushButton_clicked()
{
qDebug() << "salam";
}
main.cpp:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
You do open two times, I guess second one should be isOpen

Qt QNetworkAccessManager post method works only in main thread

I have a problem with Qt QNetworkAccessManager. I want to use it to interact with my web server which propose an POST api.
In my main function, I can use QNetworkAccessManager::post(). My server receive the data from the client.
But if I move the post function in another thread, my server receive anything.
Here an example of my code :
Worked code :
#include <iostream>
#include <QNetworkRequest>
#include <QUrl>
#include <QNetworkAccessManager>
#include <QCoreApplication>
#include <thread>
#include <QThread>
#include <QObject>
#include <QNetworkReply>
class PostClass: public QObject {
Q_OBJECT
public:
PostClass() {
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onfinish(QNetworkReply*)));
};
QNetworkAccessManager* manager = nullptr;
public slots:
void post() {
const QUrl url("http://[ip:port]/users");
QNetworkRequest req(url);
manager->get(req);
QNetworkRequest req1(QUrl("[ip:port]/event"));
req1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
qDebug() << "Send new request";
QByteArray data(R"({"data": "QtGroupHEllo"})");
manager->post(req1, data);
};
void onfinish(QNetworkReply* rep) {
qDebug() << "reply delete!";
rep->deleteLater();
qDebug() << "https post_request done!";
};
};
class ThreadTmp: public QThread {
Q_OBJECT
public:
ThreadTmp() = default;
public slots:
void onfinish(QNetworkReply* rep) {
rep->deleteLater();
qDebug() << "reply delete!";
qDebug() << "https post_request done!";
};
signals:
void postRequest();
protected:
void run() override {
while (1) {
emit postRequest();
sleep(1);
}
}
};
int main(int argc, char* argv[]) {
QCoreApplication app (argc, argv);
std::cout << "Hello, World!" << std::endl;
PostClass postObj;
ThreadTmp tmp();
QObject::connect(&tmp, SIGNAL(postRequest()), &postObj, SLOT(post()));
tmp.start();
return app.exec();
}
#include "main.moc"
But if I move the PostClass instance in my ThreadTmp class, in the run function, only get works and post doesn't work because in my server, I only received the get request and not the post request :
#include <iostream>
#include <QNetworkRequest>
#include <QUrl>
#include <QNetworkAccessManager>
#include <QCoreApplication>
#include <thread>
#include <QThread>
#include <QObject>
#include <QNetworkReply>
class PostClass: public QObject {
Q_OBJECT
public:
PostClass() {
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onfinish(QNetworkReply*)));
// connect(manager, SIGNAL(finished(QNetworkReply*)), manager, SLOT(deleteLater()));
};
QNetworkAccessManager* manager = nullptr;
public slots:
void post() {
const QUrl url("http://[ip:port]/users");
QNetworkRequest req(url);
manager->get(req);
QNetworkRequest req1(QUrl("http://[ip:port]/event"));
req1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
qDebug() << "Send new request";
QByteArray data(R"({"data": "QtGroupHEllo"})");
manager->post(req1, data);
};
void onfinish(QNetworkReply* rep) {
qDebug() << "reply delete!";
rep->deleteLater();
qDebug() << "https post_request done!";
};
};
class ThreadTmp: public QThread {
Q_OBJECT
public:
ThreadTmp() = default;
public slots:
void onfinish(QNetworkReply* rep) {
rep->deleteLater();
qDebug() << "reply delete!";
qDebug() << "https post_request done!";
};
signals:
void postRequest();
protected:
void run() override {
PostClass postObj;
connect(this, SIGNAL(postRequest()), &postObj, SLOT(post()));
while (1) {
emit postRequest();
sleep(1);
}
}
};
int main(int argc, char* argv[]) {
QCoreApplication app (argc, argv);
std::cout << "Hello, World!" << std::endl;
ThreadTmp tmp();
tmp.start();
return app.exec();
}
#include "main.moc"
I don't know why I have this behavior ...
You need to use a blocking .exec() in order to have an event loop in a thread. Just overriding run(), causes the thread to fire off that code and then terminate. When you post via the QNetworkAccessManager, that actually occurs asynchronously, in the background, driven by the QEventLoop out of the box. It should not typically be necessary to use another thread, if you are interacting with a simple REST api, or even if using a get() to download a large file. Qt handles for you, what you are probably trying to avoid with another thread, i.e. clogging up the main thread and hindering performance with network traffic. The best reason to use another thread would be to process the response from the server in the event that's going to take a long time. To do that, just hook up the signals/slots across threads, while leaving the post operation / network manager in your main one. (Generally speaking of course...)

How to receive proper UDP packet in QT?

I am trying write a QT program to receive UDP packet.I am trying to receive from Packet Sender software
This is my code
socket = new QUdpSocket(this);
bool result = socket->bind(QHostAddress("150.100.50.88"),45454);
qDebug() << result;
if(result)
{
qDebug << "PASS";
}
else
{
qDebug << "FAIL";
}
processPendingDatagrams();
connect(socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()),Qt::QueuedConnection);
void UDP::processPendingDatagrams()
{
QHostAddress sender;
u_int16_t port;
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() <<"Message From :: " << sender.toString();
qDebug() <<"Port From :: "<< port;
qDebug() <<"Message :: " << datagram;
} //! [2]
}
UDP.h:
class UDP : public QObject
{
Q_OBJECT public:
explicit UDP(QObject *parent = 0);
signals:
public slots:
void SendDatagram(u_int8_t,u_int8_t,u_int8_t);
private slots:
void processPendingDatagrams();
private :
QUdpSocket *socket;
};
The readReady signal and corresponding slot are not working . I can see the packets in Wireshark.
If a I try receive the packets in continuously in a loop I am able see the datagrams.What can be the reason for signals and Slots for not working.Sending operation is working well.
This code work for me. Try it please.
.pro:
#-------------------------------------------------
#
# Project created by QtCreator 2017-03-10T11:44:19
#
#-------------------------------------------------
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = test
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
mainwindow.cpp:
#include "mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
socket = new QUdpSocket(this);
bool result = socket->bind(QHostAddress::AnyIPv4, 45454);
qDebug() << result;
if(result)
{
qDebug() << "PASS";
}
else
{
qDebug() << "FAIL";
}
processPendingDatagrams();
connect(socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()),Qt::QueuedConnection);
}
MainWindow::~MainWindow()
{
}
void MainWindow::processPendingDatagrams()
{
qDebug() << "in !";
QHostAddress sender;
u_int16_t port;
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() <<"Message From :: " << sender.toString();
qDebug() <<"Port From :: "<< port;
qDebug() <<"Message :: " << datagram;
}
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QUdpSocket>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void processPendingDatagrams();
private:
QUdpSocket *socket = nullptr;
};
#endif // MAINWINDOW_H
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
tried with netcat with the command:
netcat -u 127.0.0.1 45454
once you ran the command, just type anything and press return.
In my case this did not work, because there was always a "dummy" datagram left somewhere in memory, even if hasPendingDatagrams() returned false, I had to call readDatagram one more time to let my program receive newer datagrams. My answer is here anyways https://stackoverflow.com/a/74056997/11414500
Good luck!
#Gabriel answer did't work for me because it's using the old connect syntax. I updated it to the following (Qt 6):
// udpclient.h
#ifndef UDPCLIENT_H
#define UDPCLIENT_H
#include <QObject>
#include <QUdpSocket>
class UdpClient: public QObject
{
Q_OBJECT
public:
explicit UdpClient(QObject *parent);
void initSocket();
private:
void processPendingDatagrams();
QUdpSocket *socket=nullptr;
};
#endif // UDPCLIENT_H
// udpclient.cpp
#include "udpclient.h"
UdpClient::UdpClient(QObject *parent) : QObject(parent) {
}
void UdpClient::initSocket()
{
socket = new QUdpSocket(this);
bool result = socket->bind(QHostAddress::AnyIPv4, 4999);
if(result)
{
qDebug() << "Socket PASS";
}
else
{
qDebug() << "Socket FAIL";
}
processPendingDatagrams();
connect(socket, &QUdpSocket::readyRead, this, &UdpClient::processPendingDatagrams);
}
void UdpClient::processPendingDatagrams()
{
qDebug() << "in !";
QHostAddress sender;
quint16 port;
while (socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
qDebug() <<"Message From :: " << sender.toString();
qDebug() <<"Port From :: "<< port;
qDebug() <<"Message :: " << datagram;
}
}
It can be used in a function or main() as:
auto udpClient = new UdpClient(0);
udpClient->initSocket();

newConnection() signal does not get emitted in QTcpSever even when I am clearly connecting to the server

QTcpServer is supposed to emit the newConnection() signal whenever it receives a new client connection. I am able to connect to the server I created, even telnet to it. But in the server implementation, I have connected the newConnection() signal to a slot and it never gets invoked.
Can you please look at my code and tell me what is it that I am doing wrong ?
First the header :
#include <data_model.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <QtNetwork>
#include <QVector>
#include <iostream>
#include <QAbstractSocket>
#include <QDebug>
class QTcpServer;
class QNetworkSession;
class superServer : public QObject
{
Q_OBJECT
public:
explicit superServer(QObject *parent = 0);
data_model::terminal_data fetch_next_record();
void route_data();
private slots:
void sessionOpened();
public slots:
void newTerminalConnection();
void errorconnecting(QAbstractSocket::SocketError socketError);
private:
QTcpServer *tcpServer;
QNetworkSession *networkSession;
QVector<QTcpSocket*> liveConnections;
};
#endif // SUPERSERVER_HPP
Now the implementation:
#include <superServer.hpp>
void superServer::newTerminalConnection()
{
qDebug() << "someone connected ...";
std::cout << "someone connected ..." << std::endl;
QTcpSocket *socket = tcpServer->nextPendingConnection();
liveConnections.push_back(socket);
}
superServer::superServer(QObject *parent) :
QObject(parent)
{
tcpServer = new QTcpServer();
if(!tcpServer->listen(QHostAddress::Any, 9889))
qDebug() << "Server could not start";
else
qDebug() << "Server started!";
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newTerminalConnection()));
connect(tcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), this, SLOT(errorconnecting(QAbstractSocket::SocketError)));
}
void superServer::errorconnecting(QAbstractSocket::SocketError socketError)
{
qDebug() << "error connecting to client";
}
Also, I am connecting like this:
void tradeView::doConnect()
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));
connect(socket, SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));
connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));
qDebug() << "connecting...";
// this is not a blocking call
socket->connectToHost("localhost", 9889);
// we need to wait...
if(!socket->waitForConnected(5000))
{
qDebug() << "Error: " << socket->errorString();
}
}
void tradeView::connected()
{
qDebug() << "connected...";
}
void tradeView::disconnected()
{
qDebug() << "disconnected...";
}
void tradeView::bytesWritten(qint64 bytes)
{
qDebug() << bytes << " bytes written...";
}
The client connects !!! Even Telnet works !!!
But that signal does not get emitted. Can you please tell me what is wrong ?
Trust me I have looked at more than a dozen related threads here on SO and qt-center etc. None give a solution.
Please help.

udp packet is not received in QThread

I'm trying to receive some packets using a udpReceiver class that I have written using qUdpSocket in a separate QThread :
class udpThread : public QThread
{
private:
QObject * parent;
public:
udpThread(QObject * parent = 0)
{
this->parent = parent;
}
void run()
{
UdpReceiver * test = new UdpReceiver(parent);
}
};
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
port = 9003;
initialize();
}
UdpReceiver(int p,QObject* parent = 0) : QObject(parent)
{
port = p;
initialize();
}
void initialize()
{
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
public slots:
void readPendingDiagrams()
{
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received .... \n";
qDebug() << " bytes received .... \n";
}
}
};
And here is the main() method :
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// UdpReceiver * net = new UdpReceiver();
MainWindow w;
udpThread * ut = new udpThread();
ut->start();
w.show();
return a.exec();
}
Now when I use the udpReceiver class to get the packets without the QThread it works just fine, but when I use the udpThread class it doesn't get the packets or at least the raedyread() signal does not activate some how.
When I try to get the packets without the QThread my GUI crashes somehow and the whole program hangs, that's why I want to use QThread.
I appreciate if you could help me solve this :)
Regards,
You've fallen into the same trap as many do when working with threads in Qt: http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/.
It is almost always a bad idea to subclass QThread (see http://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html for counterexamples).
Change your code as follows to do it the "intended" way (create a new QThread and call moveToThread on your QObject to move it to the new thread). You'll see from the output that the thread the UdpReceiver is created on is not the same as the one it receives data on, which is what you want:
#include <QApplication>
#include <QDebug>
#include <QThread>
#include <QUdpSocket>
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
qDebug() << "Construction thread:" << QThread::currentThreadId();
port = 9003;
initialize();
}
UdpReceiver(int p,QObject* parent = 0) : QObject(parent)
{
port = p;
initialize();
}
void initialize()
{
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
public slots:
void readPendingDiagrams()
{
qDebug() << "Reading thread:" << QThread::currentThreadId();
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received .... \n";
qDebug() << " bytes received .... \n";
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QThread *t = new QThread();
t->start();
UdpReceiver * net = new UdpReceiver();
net->moveToThread(t);
return a.exec();
}
#include "main.moc"
I don't have your UI code, so I don't know about any issues there. Feel free to post another question if you get stuck there and mention it in a comment and I'll try to help.
Vahid Nateghi, the init codes and the work codes must run in the same thread. But the constructor of UdpReceiver runs in the main thread against the one readPendingDiagrams runs in, that was the bug. Try this:
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QUdpSocket>
class UdpReceiver : public QObject
{
Q_OBJECT
private:
QUdpSocket * S;
int port;
public:
UdpReceiver(QObject* parent = 0) : QObject(parent)
{
qDebug() << ">HERE was the bug! thread:" << QThread::currentThreadId() << "in Construction of UdpReceiver:" << __LINE__ ;
}
public slots:
void init_thread(){
port = 10000;
qDebug() << ">thread:" << QThread::currentThreadId() << "in init_thread:" << __LINE__ ;
S = new QUdpSocket();
S->bind(port);
S->connect(S,SIGNAL(readyRead()),this,SLOT(readPendingDiagrams()));
qDebug() << "Waiting for UDP data from port " << port << " ... \n";
}
void readPendingDiagrams()
{
qDebug() << ">thread:" << QThread::currentThreadId() << "in readPendingDiagrams:" << __LINE__ ;
while(S->waitForReadyRead())
{
QByteArray datagram;
datagram.resize(S->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
S->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);
qDebug() << datagram.size() << " bytes received in thread " << QThread::currentThreadId() << "in readPendingDiagrams:" << __LINE__ ;
}
}
};
int main(int argc, char *argv[])
{
qDebug() << ">Main thread:" << QThread::currentThreadId() << "in main:" << __LINE__ ;
QCoreApplication a(argc, argv);
QThread *t = new QThread();
UdpReceiver * net = new UdpReceiver();
net->moveToThread(t);
net->connect(t,SIGNAL(started()),net,SLOT(init_thread()));
t->start();
return a.exec();
}
#include "main.moc"