I am new in Qt development and developing Qt DLL which start TCP Server.When i am calling dll from my another app it will not receive any new connection socket.
So please guide me if i am doing any wrong step.
Server.h
extern "C" SERVERSHARED_EXPORT void CallServer();
class SERVERSHARED_EXPORT Server : public QObject
{
Q_OBJECT
public:
Server();
void CallServer();
void CallServer1();
QTcpServer *server;
QTcpSocket *socket ;
signals:
public slots:
void myConnection();
void closingClient();
};
Server.cpp
Server::Server()
{
}
void CallServer()
{
Server server_Obj;
server_Obj.CallServer1();
while (true)
::sleep(1000);
}
void Server::CallServer1()
{
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()),this, SLOT(myConnection()));
QHostAddress hostadd(ServerIP);
qDebug() << ServerIP;
qDebug() << Port;
if(!server->listen(hostadd,Port.toInt())) qDebug() << "\nWeb server could not start";
else qDebug() <<"\nWeb server is waiting for a connection";
}
void Server::myConnection()
{
qDebug() << "Detected Connection";
QByteArray Rdata;
socket = server->nextPendingConnection();
qDebug() << "Wait for connect = " << socket->waitForConnected();
while (socket->waitForReadyRead(10))
{
while(socket->bytesAvailable() > 0)
{
Rdata.append(socket->readAll());
}
}
qDebug() << "Final Testing is size = " << Rdata.size();
qDebug() << "Final Testing is" << Rdata;
}
.pro file
QT += core
QT += network
QT += widgets
QT -= gui
TARGET = Server
TEMPLATE = lib
DEFINES += SERVER_LIBRARY
SOURCES += server.cpp
HEADERS += server.h\
server_global.h
Another App:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QLibrary library("Server.dll");
if (!library.load())
qDebug() << library.errorString();
if (library.load())
qDebug() << "library loaded";
typedef int(*pf)(void);
pf cwf = (pf)library.resolve("CallServer");
if (cwf) {
int x = cwf();
} else {
qDebug() << "Could not show widget from the loaded library";
}
qDebug() << "After call";
return a.exec();
}
Looks like it's not working because you are using QTcpSocket (your Server class) in asynchronous (signals/slots) way WITHOUT event loop - so it'll not work. You should add an event loop or use sockets in a blocking manner. For more details look at - http://doc.qt.io/qt-5/qtnetwork-blockingfortuneclient-example.html
Related
Here is a short UDP server example in Qt below which does work but what I don't like is that I'm polling to see if new data is available. I've come across some examples of a readyRead() but they all seem to introduce a qt class. Do I need to use a qt class in order to take advantage of the readyRead() signal?
Here is the working but simple UDP server implemented entirely in main:
#include <QDebug>
#include <QUdpSocket>
#include <QThread>
int main(int argc, char *argv[])
{
QUdpSocket *socket = new QUdpSocket();
u_int16_t port = 7777;
bool bindSuccess = socket->bind(QHostAddress::AnyIPv4, port);
if (!bindSuccess) {
qDebug() << "Error binding to port " << port << " on local IPs";
return a.exec();
}
qDebug() << "Started UDP Server on " << port << endl;
QHostAddress sender;
while (true) {
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.data();
}
QThread::msleep(20);
}
return 0;
}
Here is an example of the readyRead() signal:
https://www.bogotobogo.com/Qt/Qt5_QUdpSocket.php
I haven't really figured out how to get this to work yet. I must be doing something wrong. Here is the UDP connection code i'm trying:
#include "myudp.h"
MyUDP::MyUDP(QObject *parent) : QObject(parent) {
}
void MyUDP::initSocket(u_int16_t p) {
port = p;
udpSocket = new QUdpSocket(this);
bool bindSuccess = udpSocket->bind(QHostAddress::LocalHost, port);
if (!bindSuccess) {
qDebug() << "Error binding to port " << port << " on local IPs";
return;
}
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
void MyUDP::readPendingDatagrams() {
QHostAddress sender;
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &port);
qDebug() << "Message From :: " << sender.toString();
qDebug() << "Port From :: " << port;
qDebug() << "Message :: " << datagram.data();
}
}
myudp.h
#include <QObject>
#include <QUdpSocket>
class MyUDP : public QObject
{
Q_OBJECT
public:
explicit MyUDP(QObject *parent);
void initSocket(u_int16_t p);
u_int16_t port;
QUdpSocket *udpSocket;
signals:
public slots:
void readPendingDatagrams();
};
new main.cpp
int main(int argc, char *argv[])
{
MyUDP *myUDP = new MyUDP(0);
myUDP->initSocket(port);
while (true) {
usleep(1000);
}
return 0;
}
I am testing with:
netcat 127.0.0.1 -u 7777
{"cid"="0x1234123412341", "fill_level"=3245 }<cr>
What you're doing wrong is that you're not letting Qt's event loop run. i.e. this is incorrect:
int main(int argc, char *argv[])
{
MyUDP *myUDP = new MyUDP(0);
myUDP->initSocket(port);
while (true) {
usleep(1000);
}
return 0;
}
... instead, you should have something like this:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// connect needs to occur after QCoreApplication declaration
MyUDP *myUDP = new MyUDP(0);
myUDP->initSocket(port);
return app.exec();
}
... it is inside the app.exec() call where a Qt application spends most of its time (app.exec() won't return until Qt wants to quit), and there is where Qt will handle your UDP socket's I/O and signaling needs.
Please modify your processPendingDatagrams like this, to let newer incoming data be processed:
void MyUDP::readPendingDatagrams() {
QHostAddress sender;
uint16_t port;
QByteArray datagram; // moved here
while (udpSocket->hasPendingDatagrams()) {
//QByteArray datagram; // you don't need this here
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &port);
qDebug() << "Message From :: " << sender.toString();
qDebug() << "Port From :: " << port;
qDebug() << "Message :: " << datagram.data();
}
// God knows why, there is always one more "dummy" readDatagram call to make,
// otherwise no new readyRead() will be emitted, and this function would never be called again
datagram.resize(udpSocket->pendingDatagramSize());
socket->readDatagram(datagram.data(),datagram.size(),&sender,&port);
}
I have a Qt console application. In this application, there is an object of type "my_client". "my_client" objects have an slot named "messageSlot". This slot is connected to a DBUS message.
So the main function of this qt app is as follows :
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
if (!QDBusConnection::sessionBus().isConnected())
{
fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n");
return 1;
}
if (!QDBusConnection::sessionBus().registerService("org.brlapi.server"))
{
fprintf(stderr, "%s\n",
qPrintable(QDBusConnection::sessionBus().lastError().message()));
std::cout << qPrintable(QDBusConnection::sessionBus().lastError().message())
<< std::endl;
exit(1);
}
my_client client;
new myClassAdaptor(&client);
QDBusConnection::sessionBus().registerObject("/", &client);
QDBusConnection::sessionBus().connect("org.my.server",
"/",
"org.my.server",
"message",
&client,
SLOT(my_client::messageSlot(QString, QString)));
return a.exec();
}
And my_client is as follows :
class my_client : public QObject
{
Q_OBJECT
public:
my_client()
{
}
private slots:
void messageSlot(QString msg1, QString msg2)
{
std::cout << "CLIENT : I've received a message : " << msg1.toStdString()
<< "," << msg2.toStdString() << std::endl;
QDBusMessage msg = QDBusMessage::createSignal("/", "org.my.server", "message");
msg << "Hello!!!" << "Are you ok?";
QDBusConnection::sessionBus().send(msg);
}
};
But with this code I can't receive DBUS message. I think that the problem is that client object hasn't a main loop and therefore can't receive signals.
Am I right? If so, how can we add client object to main loop? and if not, what is the problem with this code? how can I receive dbus messages and handle them with QT signal/slot?
I am trying to read my SerialPort based on the
http://doc.qt.io/qt-5/qtserialport-creadersync-main-cpp.html
example:
QCoreApplication coreApplication(argc, argv);
QTextStream standardOutput(stdout);
QSerialPort serialPort;
QByteArray readData;
serialPort.setPortName("ttyS4");
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::EvenParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
if (!serialPort.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open port") << endl;
return 1;
}
while (serialPort.waitForReadyRead(5000))
readData.append(serialPort.readAll());
qDebug() << readData;
return coreApplication.exec();
I also tried reading Data based on the http://doc.qt.io/qt-5/qtserialport-cwriterasync-example.html example:
Main:
int main(int argc, char *argv[])
{
QCoreApplication coreApplication(argc, argv);
QTextStream standardOutput(stdout);
QSerialPort serialPort;
serialPort.setPortName("ttyS4");
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(QSerialPort::EvenParity);
serialPort.setStopBits(QSerialPort::OneStop);
serialPort.setFlowControl(QSerialPort::NoFlowControl);
if (!serialPort.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open port") << endl;
return 1;
}
SerialPortReader serialPortReader(&serialPort);
return coreApplication.exec();
}
serialPortReader:
SerialPortReader::SerialPortReader(QSerialPort *serialPort, QObject *parent):QObject(parent), m_serialPort(serialPort), m_standardOutput(stdout)
{
connect(m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead()));
connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));
connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));
m_counter = 0;
m_timer.start(5000);
}
SerialPortReader::~SerialPortReader()
{
}
void SerialPortReader::handleReadyRead()
{ m_counter++;
m_readData.append(m_serialPort->readAll());
qDebug()<< m_serialPort->readAll();
qDebug() << "triggered" << m_counter;
}
void SerialPortReader::handleTimeout()
{
if (m_readData.isEmpty()) {
m_standardOutput << QObject::tr("No data was currently available for reading from port %1").arg(m_serialPort->portName()) << endl;
} else {
m_standardOutput << QObject::tr("Data successfully received from port %1").arg(m_serialPort->portName()) << endl;
m_standardOutput << m_readData << endl;
}
QCoreApplication::quit();
}
void SerialPortReader::handleError(QSerialPort::SerialPortError serialPortError)
{
if (serialPortError == QSerialPort::ReadError) {
m_standardOutput << QObject::tr("An I/O error occurred while reading the data from port %1, error: %2").arg(m_serialPort->portName()).arg(m_serialPort->errorString()) << endl;
QCoreApplication::exit(1);
}
}
But when I send data to this COM port (with same serialPort Settings for Sender), not all of the data is received.
With the MSB-RS232 I can check which data really has been sendet to the port and there is nothing wrong with my sender.
For testing I am sending
main:
QString alpha = "abcdefghijklmnopqrstuvwxyz123456789";
handler.writetoPort(alpha);
handler.cpp:
void SerialHandler::writetoPort(QString x)
{
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QByteArray encodedVar = codec->fromUnicode(x);
writetoPort(encodedVar);
}
void SerialHandler::writetoPort(const QByteArray x)
{
serial.write(x);
serial.waitForBytesWritten(-1);
}
The result of this is the output:
abyz123456789 or abcdklmnopqrstuvwxyz123456789 or abcdefghijklm or ...
It's always different.
Does anyone have a clue what is going on here?
Thank you for reading my long post.
--added 17.07--
This might be mandatory for my problem:
The code has to run on a microprocessor.
CPU: Atmel -AT91SAM9X25 - ARM926(ARMv5) - 400MHz
RAM: 32 MB
Linux Kernel Version: 3.9.0
QT Version: 5.4.1 (cross compiled)
both the async and sync example are working perfectly fine on my Windows PC.
Maybe this will help
void SerialPortReader::handleReadyRead()
{
m_counter++;
while (m_serialPort->bytesAvailable())
{
m_readData.append(m_serialPort->readAll());
}
qDebug()<< m_readData;
qDebug() << "triggered" << m_counter;
}
I tried the exact same Projekt on a different Board and everything works smoothly.
I think the COM Port of the old Board might have been damaged.
Will mark this as resolved but I can't tell what the true problem really was.
I have a server that can handle multiple threads. The server starts and listens, but it is having trouble echoing when an incoming connection is pending.
I am using telnet to open the socket and send data to the server. However, the server only displays that it's listening, but doesn't echo any of the data I type through telnet or signify that there is an incoming connection. I shut off Windows firewall for private networks and still...nothing.
Also tried seeing if the server error string had anything useful to say, but all it is just an empty string.
This is a complete mystery to me and if anyone had anything constructive to note, it'd be much appreciated. Code for the thread and server is below.
server.cpp
#include "myserver.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::StartServer()
{
if(!this->listen(QHostAddress::Any,1234))
{
qDebug() << "Could not start server";
}
else
{
qDebug() << "Listening...";
}
}
void MyServer::incomingConnection(int socketDescriptor)
{
qDebug() << socketDescriptor << " Connecting...";
MyThread *thread = new MyThread(socketDescriptor,this);
connect(thread, SIGNAL(finished()),thread, SLOT(deleteLater()));
thread->start();
}
thread.cpp
#include "mythread.h"
MyThread::MyThread(int ID, QObject *parent) :
QThread(parent)
{ this->socketDescriptor = ID;
}
void MyThread::run()
{
qDebug() << socket->errorString();
//thread starts here
qDebug() << socketDescriptor << " Starting thread";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
qDebug() << socketDescriptor << " Client Connected";
exec();
}
void MyThread::readyRead()
{
QByteArray Data = socket->readAll();
qDebug() << socketDescriptor << " Data in: " << Data;
socket->write(Data);
}
void MyThread::disconnected()
{
qDebug() << socketDescriptor << " Disconnected";
socket->deleteLater();
exit(0);
}
Which version of Qt are you using? In Qt 5, the parameter for the function incomingConnection is of type qintptr and not int. Have a look at the following links:
incomingConnection - Qt 5
Qt 5 - Multithreaded server tutorial
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"