Setting up server for other people to connect using Qt - c++

I have a very small and simple server based on QTcpServer which just listens for new connections and once a new connection is connected it shows message about it.
Respectively, the same thing with my client. So, if i give my client app to my friend how can he connect to my seerver??? I have tested my server and client on locallhost (127.0.0.1) but never tried in the "real" world??? Can you please give me some hints???
//**SERVER**
#include <QTcpServer>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTcpServer server; //used 127.0.0.1 for localhost, but...
server.listen(???, 12345);//--->what to do to connect to the internet
return a.exec();
}
How can my friend connect to my server?
//**Client**
#include <QTcpSocket>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTcpSocket client;
client.connectToHost(???);
return a.exec();
}

Related

How to add SQLite database to resources in a Qt project

I can't add a database to resources:
#include "QtSql/QSqlDatabase"
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":/new/prefix1/database.db");
if (!db.open())
qDebug()<<"ERRR"; // this line is printed at startup
return a.exec();
}
the database is present in resources:
enter image description here

How I show application when open application again Qt

Now, I have 1 application, but I don't want to open application twice, so I using QShareMemory to detect application when open twice.
And my question is: how I show current application in screen when user open application the second ?
int main(int argc, char *argv[]) {
Application a(argc, argv);
/*Make sure only one instance of application can run on host system at a time*/
QSharedMemory sharedMemory;
sharedMemory.setKey ("Application");
if (!sharedMemory.create(1))
{
qDebug() << "123123Exit already a process running";
return 0;
}
/**/
return a.exec();
}
Thanks.
Here's another approach in pure Qt way:
Use QLocalServer and QLocalSocket to check the existence of application and then use signal-slot mechanism to notify the existing one.
#include "widget.h"
#include <QApplication>
#include <QObject>
#include <QLocalSocket>
#include <QLocalServer>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
const QString appKey = "applicationKey";
QLocalSocket *socket = new QLocalSocket();
socket->connectToServer(appKey);
if (socket->isOpen()) {
socket->close();
socket->deleteLater();
return 0;
}
socket->deleteLater();
Widget w;
QLocalServer server;
QObject::connect(&server,
&QLocalServer::newConnection,
[&w] () {
/*Set the window on the top level.*/
w.setWindowFlags(w.windowFlags() |
Qt::WindowStaysOnTopHint);
w.showNormal();
w.setWindowFlags(w.windowFlags() &
~Qt::WindowStaysOnTopHint
);
w.showNormal();
w.activateWindow();
});
server.listen(appKey);
w.show();
return a.exec();
}
But if you're using Qt 5.3 on Windows, there's a bug for QWidget::setWindowFlags and Qt::WindowStaysOnTopHint, see https://bugreports.qt.io/browse/QTBUG-30359.
Just use QSingleApplication class instead of QApplication:
https://github.com/qtproject/qt-solutions/tree/master/qtsingleapplication
int main(int argc, char **argv)
{
QtSingleApplication app(argc, argv);
if (app.isRunning())
return 0;
MyMainWidget mmw;
app.setActivationWindow(&mmw);
mmw.show();
return app.exec();
}
It is part of Qt Solutions: https://github.com/qtproject/qt-solutions

QT can't debug a simple dialog program:Signal received.The inferior stopped because it received a signal

I fail to debug a simple dialog program ,it alerts:
"Signal received.The inferior stopped because it received a signal
from the Operating System.Signal name:SIGSEGV.Signal
meaning:Segmentation fault"
I use MinGW4.8 and QT SDK 4.8 on windows.
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
It alerts at :
w.show();
When UI shows,it alerts,and can't continue the debug.How can I debug succefully?

Qt Server Client Code

I am a new to the QT programming. my server/client codes are quite simple but they are not working.......
pls have a look to find problems in my codes, thanks.
SERVER:
int main(int argc, char** argv)
{
// QApplication app(argc, argv);
// Server server;
QTcpSocket *client_sock = NULL;
QTcpServer server;
server.listen(QHostAddress::Any,8888);
char buff[100];
while(1)
{
if(server.hasPendingConnections())
{
client_sock = server.nextPendingConnection();
}
if(client_sock)
{
qint64 n_rtn;
n_rtn = client_sock->bytesAvailable();
client_sock->readLine(buff,n_rtn);
std::cout<<buff;
}
}
// return app.exec();
}
CLIENT:
int main(int argc, char** argv)
{
// QApplication app(argc, argv);
QTcpSocket client;
QHostAddress addr("127.0.0.1");
client.connectToHost(addr,8888);
if(client.isWritable())
{
client.write("Hello World!\n");
}
client.close();
// return app.exec();
}
Thanks
Without a QApplication or a QCoreApplication and an app.exec() nothing will work. This is what runs the event loop which handles all the keyboard/mouse/network events.
Take a look at the chat and fortune cookie network server examples to see how to do this - it's almost as simple as the code you have written

Experiencing timeouts after connecting to 20 different servers using QTcpSocket

I've been experiencing a weird problem using QTcpSocket, I've searched the web but can't find anybody else with the same problem.
I have two bare-bones applications, one client and one server, if I run them both on my local machine the client successfully makes all 50 connections to the server.
If I run the server on another computer connected to the network (let's say: 10.1.1.1) it will again connect every time without a problem.
Now, if I change the server's main.cpp to initialise multiple servers under different ports (8001 to 8050), and change the client to make one connection to each server. With both running locally it still works fine.
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
for (int i = 8001; i <= 8050; ++i) {
Server server(i);
return app.exec();
}
}
But, if I put the server on 10.1.1.1 and try it again then I connect to the first 20 without a problem, but then it hangs for a while (anywhere upwards of 5 seconds) before connecting to the next 20, and so on until all are connected.
As a final test, I put an instance of the server on another machine (10.1.1.2) and created 15 instances of a server on each machine and tried to connect to both I experienced the same problem. All 15 of the first machine connected fine, as did the next 5 of the 2nd machine before it hung until eventually connecting to the last 10.
This is on Qt version 4.7.2. And I've experienced this problem on Fedora 17, Windows 7 but not Scientific Linux 6.
The code for the client/server is included below, I removed all the includes to save some vertical space:
Client
client.h
class Client: public QObject {
Q_OBJECT
public:
Client(QObject* parent = 0);
~Client();
void start(QString address, quint16 port);
public slots:
void startTransfer();
void disconnect() { qDebug("disconnect"); }
private:
QTcpSocket client;
};
client.cpp
Client::Client(QObject* parent): QObject(parent) {
connect(&client, SIGNAL(connected()), this, SLOT(startTransfer()));
connect(&client, SIGNAL(disconnected()), this, SLOT(disconnect()));
}
Client::~Client() {
client.close();
}
void Client::start(QString address, quint16 port) {
QHostAddress addr(address);
qDebug(QString("connecting to %1:%2").arg(address, QString::number(port)).toLocal8Bit().constData());
client.connectToHost(addr, port);
}
void Client::startTransfer() {
qDebug("connected");
client.write("Hello, world", 13);
}
main.cpp
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
for (int i = 0; i < 50; i++) {
Client *client = new Client;
client->start("192.168.0.1", 8888);
}
return app.exec();
}
Server
server.h
class Server: public QObject {
Q_OBJECT
public:
Server(int port = 8888, QObject * parent = 0);
~Server();
public slots:
void acceptConnection();
void startRead();
private:
QTcpServer server;
QList<QTcpSocket *> clients;
};
server.cpp
Server::Server(int port, QObject* parent): QObject(parent) {
qDebug(qPrintable("new server instance on port " + QString::number(port)));
connect(&server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
server.listen(QHostAddress::Any, port);
}
Server::~Server() {
server.close();
}
void Server::acceptConnection() {
QTcpSocket *client = server.nextPendingConnection();
clients.append(client);
connect(client, SIGNAL(readyRead()), this, SLOT(startRead()));
}
void Server::startRead() {
QTcpSocket *client = dynamic_cast<QTcpSocket *>(sender());
char buffer[1024] = {0};
client->read(buffer, client->bytesAvailable());
QString response = QString("%2 on server %3").arg(buffer, QString::number(server.serverPort()));
std::cout << qPrintable(response) << std::endl;
client->close();
}
main.cpp
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
Server server;
return app.exec();
}